简体   繁体   English

如何计算来自 Django 中另一个模型的数据?

[英]How to count data from Another Model in Django?

I have 2 models and i want to count Foreignkey data, I am trying to count the number of records in related models, but I am unable to count the records, Please let me know how i can Count the data.我有 2 个模型,我想计算外Foreignkey数据,我正在尝试计算相关模型中的记录数,但我无法计算记录数,请告诉我如何计算数据。 I want to count this data after filter, I am filtering between 2 dates, it's giving me the current data of using model in filter,but i want to count related model data also using filter.我想在过滤后计算这些数据,我在 2 个日期之间进行过滤,它给了我在过滤器中使用模型的当前数据,但我想也使用过滤器计算相关模型数据。

Here is my models.py file...这是我的models.py文件...

class Product(models.Model):
    name=models.CharField(max_length=225)
    customer=models.ForeignKey(Brand, related_name='product_customer',on_delete=models.CASCADE)
    user= models.ForeignKey(Supplement, related_name='product_user', on_delete=models.CASCADE)

created_at = models.DateTimeField(auto_now_add=True) created_at = models.DateTimeField(auto_now_add=True)

here is my views.py file...这是我的views.py文件...

def index(request):
data = Project.objects.all()
  if request.method == 'POST':
     v1= request.GET.get('created-at')
     if v1:
         v2 = v1.split(' - ')
         s1 = v2[0]
         s2 = v2[1]
         result = Product.objects.filter(created_at__range=[s1,s2])
return render(request, 'index.html' {'result':result})

here is my index.html file..这是我的index.html文件..

<p>{{result.count}} product</p>
<p>{{result.product_customer.count}} Customer</p>
<p>{{result.product_user.count}} User</p>

I want to display this data after filter, for product it's working perfect, but i want to display data for customer and user when user filter...我想在过滤后显示这些数据,对于product来说它工作得很好,但是我想在用户过滤时显示customeruser数据......

I believe the fastest way to do what you want is to use the annotate function that create new fields ...我相信做你想做的最快的方法是使用创建新字段的annotate函数......

result = Product.objects.filter(created_at__range=[s1,s2]).
        annotate(count_customers=Count('customer')).
        annotate(count_users=Count('user'))

... callable in the template: ...可在模板中调用:

<p>{{result.count}} product</p>
<p>{{result.count_customers}} Customer</p>
<p>{{result.count_users}} User</p>

Check the official docs for more infos查看官方文档以获取更多信息

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

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