Django:从QuerySet获取唯一的对象列表 [英] Django: get unique object list from QuerySet

查看:291
本文介绍了Django:从QuerySet获取唯一的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Django应用程序具有以下(简化的)模型:

I have the following (simplified) models in my Django app:

class Color(models.Model):
    name = models.CharField(max_length=10)

class Item(models.Model):
    name = models.CharField(max_length=200)
    color = models.ForeignKey(Color, blank=True, null=True)

class Favorite(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)

我目前正在使用以下查询获取所需的所有项目:

I'm currently getting all the items I need using the following query:

favorites = Favorite.objects.filter(user=request.user)

如何在 QuerySet 中获取项目的所有不同颜色?

How can I get all the distinct colors for the items in that QuerySet?

我需要一个实际颜色对象的列表,而不仅仅是颜色ID,我可以使用

I need the a list of the actual color objects, not just the color ids, which I can get using

favorites.values_list('item__color').distinct


推荐答案

如果我对您的理解正确,以下方法可以解决问题:

If I understand you correctly, the following should do the trick:

favorites = Favorite.objects.filter(user=request.user)
color_ids = favorites.values_list('item__color', flat=True).distinct()
colors = Color.objects.filter(id__in=color_ids)

不过,必须有一种更清洁的方法。

There has to be a cleaner way than that though.

编辑: 更清洁的解决方案:

colors = Color.objects.filter(item__favorite__user=request.user).distinct()

这篇关于Django:从QuerySet获取唯一的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆