【问题标题】:filter on foreign and many to many relationship field过滤外国和多对多关系字段
【发布时间】:2016-07-12 06:03:15
【问题描述】:

我正在努力为我的项目获取正确的查询。这是我的模型的一个例子:

from django.db import models

class Brand(models.Model):
    name = models.CharField(max_length=30)
    handle = models.SlugField(max_length=30, unique=True, null=True, blank=True)
    def __unicode__(self):
        return self.name

class Product(models.Model):
    product_id = models.SlugField(unique=True)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, blank=True, null=True)
    collections = models.ManyToManyField('Collection')
    def __unicode__(self):
        return self.product_id

我正在尝试根据Product.collection 的值获取所有Brand_name

例如:鞋子是Product.collection,我想得到所有Brand_namecollection - 鞋子

我也试过__ 方法。不知何故,它不起作用。

【问题讨论】:

  • 什么是'Collection'?如果你有一个模型Collection 说有一个属性type(CharField),那么你可以将多对多字段声明为collections = models.ManyToManyField(Collection),你可以过滤所有shoes(假设鞋子是由Collection.type == 'shoe') 通过shoes = collections.filter(type='shoe') 识别。或者有CollectionBrand 并且您希望Brand.name == 'shoe' 成为True?你的问题不是很清楚。

标签: python django django-models foreign-keys many-to-many


【解决方案1】:
Brand.objects.filter(
    product__collection=product.collection
).values_list('name', flat=True).distinct()

productProduct 的实例。

【讨论】:

    【解决方案2】:

    related_name 添加到您的foreign key,如下所示,

    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, blank=True, 
                              null=True, related_name='products')
    

    然后你可以尝试下面的查询,它会返回一个list,其中包含product__collections_name='Shoes'

    Brand.objects.filter(products__collections__name='Shoes').values_list('name', flat=True)
    

    【讨论】:

    • 如果您选择'brands' 作为related_name 可能有点误导,它应该是'products' 因为它指的是那个。
    【解决方案3】:

    你应该试试这样的:

    Brand.objects.product_set.filter(collections__name="Shoes").values('brand__name')
    

    【讨论】:

    • Brand.objects.product_set.filter 将返回模型Product 的查询集,但Product 没有属性name(根据values('name') 的要求)。 all 也应该被忽略。我认为@dreamer 想要所有Brand.name 基于Product 的某些属性。
    • 你是对的,那么我们可以将 'name' 替换为 'brand__name'。
    猜你喜欢
    • 2023-03-06
    • 2021-08-12
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多