开发者

save or update for a model in Django Admin

I have the following structure:

class A(models.Model):
    a = models.ForeignKey(B, unique=True)
    b = models.IntegerField(default=0, blank=True)

    def save(sel开发者_JAVA技巧f, *args, **kwargs):
        self.b += 1
        super(A, self).save(*args, **kwargs)

I wanted to increment "b" by 1 whenever its saved. This works fine when I add the item the first time otherwise it fails because of the "uniqueTrue" clause.

How do I let Django "update if exists" otherwise "create new". The model does just increments the count.

Thanks.


The creation happens when you get an object. If you have a problem with saving duplicates, that is probably where you should be looking.

A.objects.get_or_create()

should get an object if it exists, create otherwise. You can examine it's pk to see if it is the same object, or a duplicate. Refer the documentation.


You can check if "self.id" existe. If it is True, then you are updating, else you are creating a new record.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜