is there a function to count a particular choice field from the feedback model in django?

In django models you can add a property method to a model in which you can reference from anywhere. You can do this by putting the @property decorator and then a function.

class Feedback(models.Model):
    customer_name = models.CharField(max_length=120)
    email = models.EmailField()
    Place = models.CharField(max_length=120)
    Area_Type = models.ForeignKey(Product, on_delete=models.CASCADE)
    Electricity = models.CharField(max_length=3, choices=[('1','Excellent'),('2','Good'),('3','Bad')])
    Water_Supply = models.CharField(max_length=3, choices=[('1', 'Excellent'), ('2', 'Good'), ('3', 'Bad')])
    details = models.TextField()
    Satisfactory_locality = models.BooleanField()
    date = models.DateField(auto_now_add=True)

    @property
    def get_feedback_count(self):
        return Feedback.objects.all().filter(Electricity='1').count()

To pass it to the view you can add it to the context in the views.py as count = Feedback.get_feedback_count()

There is a way to get it from the template using with but i forgot right now.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top