简体   繁体   中英

Is there any function to count a particular choice field from feedback model in django?

        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)
  1. I have created the above model in Django.
  2. From this I want to count number of feedback choices that are Excellent for Electricity field.
  3. Please also tell about how to view this count.
  4. Do ask if any more information required.
  5. It is showing unresolved attribute when Feedback.objects is used as shown below
class ClubChartView(TemplateView):
  template_name = 'clubs/chart.html'
  def get_context_data(self, **kwargs):
      context = super().get_context_data()
      context["qs"] = Feedback.objects.all()
      return context

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.

this question already answered here

examples:

>>> Model.objects.count()
42
>>> Model.related_set.count()
102
>>> Model.related_set.filter(blah=42).count()
3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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