I have the following doubt: Let's assume that my Django project has the following models:

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

So i have a form to add Foo instances to my db:

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

this is the view.py file:

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

I need that, every time the user registers a new 'Foo' the counter of the 'State' chosen by him is increased by 1, i search a lot here and in docs of Django but i could not find a way to do this.

2 Answers

Alex On Best Solutions

Why do you need count defined as a model field if it's dependent on a database computation, and not something that will be entered from outside?

As mentioned before, you can add logic in the application to update count value from State to self.foo_set.count()

However, I think that it might worth looking into a different approach which would be defining a cached_property on State as it follows:

def count(self):
    return self.foo_set.count()

In this way, you'll be able to access State.count wherever you want in the application and get the right value without worrying to keep it updated.

Community On

You may not need to keep track of count manually like that. For any instance of State you can always call:


That will always give you the current count.