简体   繁体   English

是否有任何函数可以从 django 的反馈模型中计算特定的选择字段?

[英]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.我已经在 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当使用 Feedback.objects 时,它显示未解析的属性,如下所示
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.在 Django 模型中,您可以将属性方法添加到模型中,您可以在其中从任何地方引用。 You can do this by putting the @property decorator and then a function.您可以通过放置@property装饰器和一个函数来做到这一点。

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()要将其传递给视图,您可以将其添加到views.py的上下文中作为count = Feedback.get_feedback_count()

There is a way to get it from the template using with but i forgot right now.有一种方法可以使用with从模板中获取它with但我现在忘记了。

this question already answered here这个问题已经在这里回答

examples:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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