9
9
95506682020-12-12 16:59:53
Django
9550668, 2020-12-12 16:59:53

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()


Table AvatarVideo:
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()}'


When the def delete function is called, which should delete the instance and file from the system, it also deletes the entry in NewModel, to which the AvatarVideo entry itself belongs.

P.S.
I thought that the problem was in keep_parents - I set both True and False, but nothing has changed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Eremin, 2020-12-12
@9550668

You specify for ForeignKey models.CASCADE, so it removes all related records. Set models.SET_NULLor 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 question

Ask a Question

731 491 924 answers to any question