Django:从QuerySet获取唯一对象列表

时间:2021-02-12 01:34:40

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

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

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?

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

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

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

favorites.values_list('item__color').distinct

3 个解决方案

#1


23  

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


6  

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).

您可能必须在外键上设置一些related_names,如果这些不是默认值(我永远不会记住默认值)。

#3


0  

Can you do:

你可以做:

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

#1


23  

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


6  

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).

您可能必须在外键上设置一些related_names,如果这些不是默认值(我永远不会记住默认值)。

#3


0  

Can you do:

你可以做:

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