Django模型查询

时间:2015-05-04 07:40:57

标签: python sql django postgresql

我对Django查询模型有疑问。我知道如何编写简单的查询,但我不熟悉两个表上的LEFT JOIN。所以你能否就他的问题给我一些建议,以便更好地理解DJango ORM。

查询

select
    count(ips.category_id_id) as how_many,
    ic.name
from
    izibizi_category ic
left join
    izibizi_product_service ips
on
    ips.category_id_id = ic.id
where ic.type_id_id = 1 
group by ic.name, ips.category_id_id

从这个查询我得到结果:

How many | name
0;"fghjjh"
0;"Papir"
0;"asdasdas"
0;"hhhh"
0;"Boljka"
0;"ako"
0;"asd"
0;"Čokoladne pahuljice"
0;"Mobitel"
2;"Čokolada"

我也尝试过他的Django查询:

a = Category.objects.all().annotate(Count('id__category',distinct=True)).filter(type_id=1)

但没有结果。

我的模特:

models.py

class Category(models.Model):
    id = models.AutoField(primary_key=True)
    type_id = models.ForeignKey('CategoryType')
    name = models.CharField(max_length=255)


    def __str__(self):
        return str(self.name)


class Product_service(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, blank=True, null=True)
    selling_price = models.DecimalField(decimal_places=5, max_digits=255, blank=True, null=True)
    purchase_price = models.DecimalField(decimal_places=5, max_digits=255, blank=True, null=True)
    description = models.CharField(max_length=255, blank=True, null=True)
    image = models.FileField(upload_to="/", blank=True, null=True)
    product_code = models.CharField(max_length=255, blank=True, null=True)
    product_code_supplier = models.CharField(max_length=255, blank=True, null=True)
    product_code_buyer = models.CharField(max_length=255, blank=True, null=True)
    min_unit_state = models.CharField(max_length=255, blank=True, null=True)
    state = models.CharField(max_length=255, blank=True, null=True)
    vat_id = models.ForeignKey('VatRate')
    unit_id = models.ForeignKey('Units')
    category_id = models.ForeignKey('Category')

如果你能帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

您应该在category_id字段中添加相关名称,如:

category_id = models.ForeignKey('Category', related_name="product_services")

以便您可以在查询中执行以下操作:

a = Category.objects.all().annotate(Count('product_services',distinct=True)).filter(type_id=1)

然后您可以访问个人计数:

a[0].product_services__count