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)
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
答案 0 :(得分:1)
在django模型中,您可以向模型添加属性方法,在其中可以从任何地方进行引用。您可以先放置@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()
要将其传递给视图,您可以将其作为views.py
添加到count = Feedback.get_feedback_count()
中的上下文中
有一种方法可以使用with
从模板中获取它,但是我现在忘记了。
答案 1 :(得分:0)
此问题已经回答here
示例:
>>> Model.objects.count()
42
>>> Model.related_set.count()
102
>>> Model.related_set.filter(blah=42).count()
3