There are two models:

class Question(models.Model): question_text = models.CharField(max_length=200) count_choice= models.IntegerField(default=0) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text 

View from admin django

View from admin django It is necessary for me, so that when creating a question model in the count_choice column, the number of the choice was recorded, how to do this?

    1 answer 1

    In admin.py

     class QuestionAdmin(admin.ModelAdmin): def save_formset(self, request, form, formset, change): super(QuestionAdmin, self).save_formset(request, form, formset, change) obj = form.save(commit=False) choices_count = Choice.objects.filter(question=obj).count() obj.count_choice=choices_count obj.save() 

    Note that in this case, QuestionAdmin is overridden, not ChoiceAdmin. And it works in any operations, not only creation. You can add a check to the change argument, but then count_choice will have the wrong value when deleting options.

    • I added, as you wrote, when you create and click the Save button in the admin panel, the count_choice field is not populated. Something needs to be edited in your code? - Repa
    • And the truth is, inlines are saved differently. I'll fix it now. - Sergey Gornostaev
    • replace super (PollAdmin, self) with super (QuestionAdmin, self) and filter (poll = obj) with filter (question = obj) and it works specifically for my case. Thank! - Repa
    • He tried on one of his projects :) - Sergey Gornostaev