django 不使用相异方法的筛选模型

kupeojn6  于 2022-11-26  发布在  Go
关注(0)|答案(4)|浏览(107)

我有一个包含产品列表的模型。每个产品都有一个ID,价格,品牌等。我想返回模型中所有品牌名称不同的对象。我目前使用的是django的内置SQLite,所以它不支持类似

products = Product.objects.all().distinct('brand')

是否有其他方法可以返回品牌名称不同的所有对象?

vwkv1x7d

vwkv1x7d1#

因为SQLight不支持.distinct('field'),所以你需要直接在python中执行这个操作。例如:

products = list({p.brand: p for p in Product.objects.all()}.values())
i2byvkas

i2byvkas2#

您可以使用两种不同的方法:
1.定义方法名称(自身):

query = """
     SELECT DISTINCT brand FROM Product;
     """
self.execute(query)

1.产品=产品.对象.raw(“"”SELECT DISTINCT brand FROM产品;“"”)
请回复此邮件如果您有任何困难获取。

vulvrdjw

vulvrdjw3#

好吧,那就试试

distinctBrands = Product.objects.values('brand').annotate(count=Count('brand')).filter(count=1)

products = Products.objects.filter(
    brand__in=distinctBrands 
).all()
3xiyfsfu

3xiyfsfu4#

试试这个

products = set(Product.objects.values_list('brand'))

相关问题