python - Django模型查询

标签 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)

但没有结果。

我的模型:

模型.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')

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

最佳答案

您应该在 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

关于python - Django模型查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30024968/

相关文章:

php - 如何重建没有重复和其他限制的数组?

python - 从 Django 下载的 docx 文件已损坏

python - Django 中命名空间模板的优雅方式

python - 如何在python中向描述符或属性添加方法

sql - Ruby on Rails : Basic parameterized queries and URL formation

python - 在 python 中解压枚举的 zip

sql - Spark sql 中的广播连接(Spark 1.6.2)

django - 以django-crispy-forms创建控件行

python - 来自 API 请求的 JSON 打印嵌套列表

python - 如何比较 u'string' 和 'string' ?