简体   繁体   English

计算Django中的外键

[英]Count foreign key in django

I am doing some statistics between products and suppliers in django 1.11 with python3, the problem is that I do not know how to relate the model: 我正在使用python3在django 1.11中的产品和供应商之间进行一些统计,问题是我不知道如何关联该模型:

class Proveedor(models.Model):
    nombre_empresa = models.CharField(max_length=150)
    direccion = models.TextField()
    telefono = models.IntegerField()
    fecha_registro = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.nombre_empresa

class Producto(models.Model):
    nombre_producto = models.CharField(max_length=150)
    descripcion = models.TextField()
    precio = models.IntegerField()
    proveedor = models.ForeignKey(Proveedor)
    fecha_registro = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.nombre_producto

With the following sql statement: 用下面的sql语句:

select nombre_empresa,count(prod.id_proveedor) from productos prod,proveedores prov where prod.id_proveedor=prov.id_proveedor group by nombre_empresa

My code : 我的代码:

from app.models import Producto,Proveedor

productos = Producto.objects.all() # How do I do the filter ?
for producto in productos:
    nombre_producto = producto.nombre_producto
    proveedor = len(producto.proveedor)

I need to see the name of the suppliers with the quantity products that each supplier 我需要查看供应商的名称以及每个供应商的数量产品

How can I make the same relation to load a list with that result? 如何建立相同的关系以加载具有该结果的列表?

To get all the suppliers with the number of products of each of them you can use annotate() 要获得所有供应商的产品数量,可以使用annotate()

sup_with_prod = Proveedor.objects.annotate(num_prod=Count('producto'))

and you can access the number of products like so: 您可以这样访问许多产品:

sup_with_prod[0].num_prod

for the first supplier, and so on. 对于第一个供应商,依此类推。 Or, in your case: 或者,在您的情况下:

for supplier in sup_with_prod:
    nr_products = supplier.num_prod

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

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