【问题标题】:How to count data from Another Model in Django?如何计算 Django 中另一个模型的数据?
【发布时间】:2020-09-28 04:47:53
【问题描述】:

我有 2 个模型,我想计算 Foreignkey 数据,我正在尝试计算相关模型中的记录数,但我无法计算记录,请告诉我如何计算数据。我想在过滤后计算这些数据,我在两个日期之间进行过滤,它给了我在过滤器中使用模型的当前数据,但我想也使用过滤器来计算相关模型数据。

这是我的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)

这是我的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})

这是我的index.html 文件..

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

我想在过滤后显示这些数据,因为 product 它运行良好,但我想在用户过滤时显示 customeruser 的数据...

【问题讨论】:

    标签: python django django-models django-views django-templates


    【解决方案1】:

    我相信做你想做的最快的方法是使用 annotate 函数来创建新字段...

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

    ...可在模板中调用:

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

    查看官方docs了解更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 2021-09-21
      • 2020-08-08
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多