简体   繁体   English

Django模型查询

[英]Django model query

I have question about Django query models. 我对Django查询模型有疑问。 I know how to write simple query, but Im not familiar with LEFT JOIN on two tables. 我知道如何编写简单的查询,但是我对两个表上的LEFT JOIN不熟悉。 So can you give me some advice on his query for better understanding DJango ORM. 因此,您能给我一些有关他的查询的建议,以便更好地了解DJango ORM。

query 询问

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

From this query I get results: 从此查询中,我得到结果:

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

And I have also try with his Django query: 我也尝试使用他的Django查询:

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

But no results. 但是没有结果。

My models: 我的模特:

models.py 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')

If you culd help me on this problem. 如果您能帮助我解决这个问题。

You should add a related name on the category_id field like: 您应该在category_id字段上添加一个相关名称,例如:

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

so that in your query you can do: 这样您就可以在查询中执行以下操作:

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

and then you can access the individual counts as: 然后您可以按以下方式访问各个计数:

a[0].product_services__count

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

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