Django: get unique object list from QuerySet

强颜欢笑 提交于 2020-01-12 06:37:23

问题


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)

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

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

回答1:


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.

Edit: A much cleaner solution:

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



回答2:


Can you do:

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

You might have to set some related_names on your foreign keys if these aren't the defaults (I can never remember the defaults).




回答3:


Can you do:

favorites = Favorite.objects.filter(user=request.user).distinct('item__color')



回答4:


The is values_list(*fields, flat=False, named=False) method, so run it on your objects, for example:

user.groups.values_list('name', flat=True)


来源:https://stackoverflow.com/questions/7590692/django-get-unique-object-list-from-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!