4
 class Item(models.Model):
 name = models.CharField(max_length=20)

 class Meals(models.Model):
 name = models.CharField(max_length=50)
 ingredients = models.ManyToManyField(Item, through='MealRecipe')


 class Menu(models.Model):
 name = models.CharField(max_length=50)
 meals = models.ManyToManyField(Meals,through='CompMenu')


 class CompMenu(models.Model):
 TYPE_COMP = (
     ('B', 'Breakfast'),
     ('L', 'Lunch'),
     ('D', 'Dinner')
 )
 menu = models.ForeignKey(Menu)
 meal = models.ForeignKey(Meals)
 type = models.CharField(max_length=1, choices=TYPE_COMP)

 class MealRecipe(models.Model):
 meal = models.ForeignKey(Meal)
 item = models.ForeignKey(Item)
 qty = models.IntegerField()

If i need to serialze queryset how can i do it, there is no documentation about it, i need a JSON with Item_id, Item_name, MealRecipe_qty. Do i have to serialze all models ? I need this to manipualte the recipe quantities on the front end based on the selected menu.

 receipes = MealRecipe.objects.filter(meal__in=meals_of_menu)
 for receipe in receipes:
 name = receipe.item.name
 qty = receipe.qty

OR

 MealRecipe.objects.filter(meal__menu=some_menu_instance).distinct()

I cannot figure out how to pass the result o this query to the front end

1 Answer 1

3

For your requirements of Item_id, Item_name, MealRecipe_qty, you will need to serialize the MealRecipe model and the Item model.

Also give a related name to item in MealRecipe model

class MealRecipe(models.Model):
    meal = models.ForeignKey(Meal)
    item = models.ForeignKey(Item,related_name='qty')
    qty = models.IntegerField()

And your serializers will be

class MealRecipeSerializer(serializers.ModelSerializer):

    class Meta:
        model = MealRecipe
        fields = ('qty')

class ItemSerializer(serializers.ModelSerializer):

    qty = MealRecipeSerializer()
    class Meta:
        model = Item
        fields = ('id','name','qty')

Also if you are passing a queryset to a serializer do it as, MealRecipeSerializer(many=True)

Sign up to request clarification or add additional context in comments.

2 Comments

It worked, but i used MealRecipe.objects.all(), can i use MealRecipe.objects.filter(meal__menu=some_menu_instance).distinct() result as the queryset for my serializer?
Should work. If the query provides a queryset of MealRecipe objects it should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.