Django distinct查询仍然返回重复项



我有一个购物清单,可以通过添加食谱中的所有成分来填写。我想查询Shopping以查看是否在购物列表中显示所有独特的食谱,但是我的独特查询返回重复?

#query
ShoppingItems.objects.filter(user=account, shoppingList=shoppingList, recipe__isnull=False).values('recipe').distinct()
#returns > <ShoppingItemsQuerySet [{'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}, {'recipe': 47}]>

#shopping/models.py
class ShoppingLists(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
class ShoppingItemsQuerySet(models.QuerySet): 
def by_user_id(self, user_id):
return self.filter(user_id=user_id)
class ShoppingItemsManager(models.Manager):
def get_queryset(self):
return ShoppingItemsQuerySet(self.model, using=self._db)
class ShoppingItems(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
shoppingList = models.ForeignKey(ShoppingLists, on_delete=models.CASCADE)
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=220, blank=True, null=True) # chicken
objects = ShoppingItemsManager()
# recipes.models.py
class Recipe(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
image = models.ImageField(upload_to='image/', blank=True, null=True)
name = models.CharField(max_length=220) # grilled chicken pasta
class RecipeIngredient(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL)

如果您想从特定字段中选择不同的值,则建议指定该字段和id,这样会更精确

为了放入代码,在您的情况下,区别更像是:

ShoppingItems.objects.filter(user=account, shoppingList=shoppingList, recipe__isnull=False).distinct('id', 'recipe').values('recipe')