E
E
EgorLee2021-09-13 01:53:23
Django
EgorLee, 2021-09-13 01:53:23

How to correctly display the data in the serializer?

I have the following models :
models.py

class Ingredient(models.Model):
    name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.name


class Tag(models.Model):
    name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.name


class Recipe(models.Model):
    title = models.CharField(max_length=255)
    photo = models.ImageField(upload_to="recipe_photo/", blank=True)
    lvl_skill = models.CharField(max_length=50)
    country_kitchen = models.CharField(max_length=255)
    category = models.CharField(max_length=255)
    step_cooking = models.TextField()
    tags = models.ManyToManyField(Tag)
    ingredients = models.ManyToManyField(Ingredient, through='Ingredient_count')

    def __str__(self):
        return self.title

    class Meta:
        ordering = ('title',)

class Ingredient_count(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True)
    ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE, null=True)
    count = models.CharField(max_length=255)

    def __str__(self):
        return self.ingredient.name


To get data from Ingredient_count in serializers.py I use:

class RecipeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Recipe
        fields = ['title', 'ingredient_count_set']
        depth = 1


and in response I get this structure:
{'ingredient_count_set': [OrderedDict([('id', 350373), ('count', '100 g'), ('recipe', 40887), ('ingredient', 7951 )]), OrderedDict([('id', 350372), ('count', '100g'), ('recipe', 40887), ('ingredient', 8433)]), OrderedDict([('id ', 350374), ('count', '1 items'), ('recipe', 40887), ('ingredient', 7861)]), OrderedDict([('id', 350375), ('count' , '1 item'), ('recipe', 40887), ('ingredient', 7901)])]}

Am I getting the data from the adjacent table correctly? If not, how is it right?
And how to make it so that the name field would be shown instead of id?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stefan, 2021-09-13
@MEDIOFF

What does right or wrong mean? Explain what you want to get, like this the name should not be displayed:

def __str__(self):
        return self.ingredient.name

For you have a request to the database to get a name, which is not good.
If you want the name to be displayed, then read how to serialize related models

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question