简体   繁体   English

Django模型中的字段分配

[英]Assignment of field in Django model

I add a method to PictureBook model, 我在PictureBook模型中添加了一个方法,

class PictureBook(models.Model):
    license = models.CharField(max_length=200, unique=True)
    activate_count = models.IntegerField(default=0)

    # check if the license is available.
    def activate(self, license=None):
        if self.activate_count != 2 and self.license == license:
            import pdb; pdb.set_trace()
            self.activate_count += 1
            return True
        else:
            return False

then call activate() in views.py , I have added 然后在views.py调用activate() ,我已经添加了

import pdb; pdb.set_trace()

then I see output, 然后我看到输出

-> self.activate_count += 1
(Pdb) 

I type 'c', program continue. 我输入“ c”,程序继续。 And I check the value activate_count in admin, it should be 1, but it still 0. Thanks in advance. 我在admin中检查了activate_count的值,它应该为1,但仍然为0。在此先感谢。

您没有保存模型实例。

You have to add self.save() after you increase it, so that it actually saves your changes: 您必须在增加self.save()之后添加它,以便它实际上保存您的更改:

def activate(self, license=None):
        if self.activate_count != 2 and self.license == license:
            import pdb; pdb.set_trace()
            self.activate_count += 1
            self.save()
            return True
        else:
            return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM