Home > front end >  values_list query is returning the foreign keys pk rather than it's value
values_list query is returning the foreign keys pk rather than it's value

Time:01-05

I am trying to get all the categories currently used in Recipes without any duplicates, by querying CategoryToRecipe.

class Category(models.Model):
        name = models.CharField(max_length=50, null=True, blank=True)
    
        def __str__(self):
            return self.name

class CategoryToRecipe(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    name = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)


query_set = CategoryToRecipe.objects.values_list('name', flat=True).distinct()

query_set is returning numbers, which I assume are the ID for Category, not the name (e.g. Lunch, Dinner, etc.).

How do I get the actual name string of Category?

CodePudding user response:

As @WillemVanOnsem said in comments you are not accessing the related object name attribute you do that using joins and which is done in ORM like this:

query_set = CategoryToRecipe.objects.values_list('name__name', flat=True).distinct()
  •  Tags:  
  • Related