保存后删除对象 - Django

时间:2017-11-28 07:44:04

标签: python django django-models

我在保存Django后遇到有关删除对象的问题 我有模特喜欢:

class Reaction(models.Model):
    REACT_TYPES = (
        (LIKE, 'Like'),
        (LOVE, 'Love'),
    )
    user = models.ForeignKey(User)
    react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='LIKE')

如何撰写save(): 保存时,应使用 THE SAME user和react_type 删除可用对象,或者如果对象不存在则创建一个。

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        user = Reaction.objects.filter(user=self.user)
        react_type = Reaction.objects.filter(user=self.react_type)
        # Model delete if exist
        if self.id.exists() & self.react_type.exists() :
            self.Reaction.delete()
        # Model create if not exist
        else :
            self.Reaction.create()

修复@dirkgroten解决方案:

class ReactionManager(models.Manager):
    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        similars = Reaction.objects.filter(user=self.user, react_type=self.react_type)

        if similars.exists():
            print ('exist')
            similars.delete()
        else:
            print ('Not exist')
            similars.create()
    super(Reaction, self).save(*args, **kwargs)

2 个答案:

答案 0 :(得分:1)

请检查此代码。它可能对你有所帮助:

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    similars, created = Reaction.objects.get_or_create(user=self.user, react_type=self.react_type)

    if not created:
        print ('exist')
        similars.delete()
    super(Reaction, self).save(*args, **kwargs)

答案 1 :(得分:0)

此代码可以正常工作。

def save(self, force_insert=False, force_update=False, *args, **kwargs):
        similars = Reaction.objects.filter(user=self.user, content_type=self.content_type, object_id=self.object_id)
        if similars.exists():
            similars.delete()
            similars.update(user=self.user, react_type=self.react_type)
        else :
            similars.update(user=self.user, react_type=self.react_type)
        super(Reaction, self).save(*args, **kwargs)