如何增加我的外键模型的计数器

时间:2019-04-21 21:36:21

标签: django

我有以下疑问: 假设我的Django项目具有以下模型:

class State(models.Model):
    initials = models.CharField('Initials', max_length=2, blank = False)
    name     = models.CharField('State', max_length=50, blank = False)
    count    = models.IntegerField('Foo Counter', default=0)
    ....


class Foo(models.Model):
   name  = models.CharField('Name', max_length=50, blank = False)
   state = models.ForeignKey(State, verbose_name='State', related_name='state_fk', on_delete=models.DO_NOTHING),
   .... 

所以我有一种将Foo实例添加到我的数据库中的表单:

class FooForm(forms.ModelForm):
   class Meta:
       model  = Foo
       fields = '__all__' 

这是view.py文件:

def home(request):
    template_name = 'home.html'
    form = FooForm(request.POST or None)
    if form.is_valid():
        salvar = form.save(commit=False)
        salvar.save()
        return redirect('FooApp:home')
    else:
        context = {
            'form': form
        }
        return render(request, template_name, context)

我需要,每当用户注册一个新的“ Foo”时,他选择的“状态”的计数器就会增加1,我在这里和Django文档中进行了大量搜索,但是我找不到方法做这个。

2 个答案:

答案 0 :(得分:0)

您可能不需要像这样手动跟踪计数。对于任何State实例,您都可以随时致电:

state.foo_set.count()

这将始终为您提供当前计数。

答案 1 :(得分:0)

如果count依赖于数据库计算,而不是从外部输入的内容,为什么需要将count定义为模型字段?

如前所述,您可以在应用程序中添加逻辑以将State的值从self.foo_set.count()更新为cached_property

但是,我认为可能值得研究另一种方法,该方法将在State上定义一个@cached_property def count(self): return self.foo_set.count() ,如下所示:

State.count

通过这种方式,您将可以在应用程序中的任何位置访问rewrite并获得正确的值,而不必担心对其进行更新。