【问题标题】:Find models that have only one particular related model查找只有一个特定相关模型的模型
【发布时间】:2019-07-27 00:10:00
【问题描述】:

考虑以下模型:

class Product(models.Model):
    name = models.CharField(max_length=...)

class Size(models.Model):
    name = models.CharField(max_length=...)
    products = models.ManyToManyField(Product, through=ProductXSize,
        related_name='sizes', related_query_name='size')

class ProductXSize(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE,
        related_name='productxsizes', related_query_name='productxsize')
    size = models.ForeignKey(Size, on_delete=models.CASCADE,
        related_name='productxsizes', related_query_name='productxsize')

我想要实现的是:

for p in Product.objects.filter(sizes=[Size.object.get(...)]):
    ...

也就是说,查找具有一种尺寸和特定尺寸的产品。

【问题讨论】:

  • 那么您需要获取所有只有一种特定尺寸的产品吗? P.S 为什么你的Product 中没有尺寸 FK 作为 ForeighKey?您是否需要在 ProductXSize 模型中添加额外的尺寸字段,因为您可以通过 product 获得尺寸。
  • @SergeyPugach 我在Product 模型中没有FK,因为关系是多对多的。而且我不明白为什么我需要额外的尺寸字段。

标签: django django-models many-to-many django-orm


【解决方案1】:

您需要使用聚合值注释查询集:

https://docs.djangoproject.com/en/2.1/topics/db/aggregation/#filtering-on-annotations

Product.objects.annotate(size_cnt=Count('size'))\  # annotate
    .filter(size_cnt=1)\  # keep all that have only one size
    .filter(size=...).all()  # keep all with a certain size

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多