Answer the question
In order to leave comments, you need to log in
Why is the parent record removed?
Hello everyone once again)
I have a model:
class NewModel(models.Model):
id = models.AutoField(primary_key=True)
creator = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='created', verbose_name='Owner')
avatar = models.ForeignKey(Avatar, on_delete=models.CASCADE, null=True, default=None)
video = models.ForeignKey(AvatarVideo, on_delete=models.CASCADE, null=True, default=None)
def set_avatar(self, image):
if self.avatar is not None:
self.avatar.delete()
self.avatar = Avatar.upload_image(image=image, owner_type='marathon', picture_type='avatar')
self.save()
def set_video(self, video):
if self.video is not None:
self.video.delete()
self.video = AvatarVideo.upload_video(video=video, owner_type='marathon', video_type='avatar-video')
self.save()
class AvatarVideo(models.Model):
local_url = models.FileField(upload_to=upload_to)
url_to_upload = models.CharField(max_length=200, default='')
class Meta:
verbose_name = "Avatars.Video"
verbose_name_plural = "Avatars.Videos"
@staticmethod
def upload_video(video, owner_type, video_type):
video_name = AvatarVideo.get_uuid_name_with_extension(video)
video = AvatarVideo.objects.create(
local_url=video,
url_to_upload=Uploader.get_path(owner_type, video_type, video_name)
)
return video
def delete(self, using=None, keep_parents=True):
os.remove(self.url_to_upload)
super().delete(using=using, keep_parents=keep_parents)
@staticmethod
def get_uuid_name_with_extension(video):
video = pathlib.Path(video.name).suffix
uuid_name = uuid.uuid4()
return f'{uuid_name}{video.lower()}'
Answer the question
In order to leave comments, you need to log in
You specify for ForeignKey models.CASCADE
, so it removes all related records. Set models.SET_NULL
or models.DO_NOTHING
, depending on what kind of database behavior you want to get when deleting related records...
Documentation: https://djbook.ru/rel3.0/ref/models/fields.html#ar...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question