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()
如果我需要序列化queryset我该怎么做,没有关于它的文档,我需要一个带有Item_id,Item_name,MealRecipe_qty的JSON。我必须序列化所有型号吗?我需要这个来根据所选菜单操作前端的配方数量。
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()
我无法弄清楚如何将此查询的结果传递给前端
答案 0 :(得分:1)
根据您对Item_id,Item_name,MealRecipe_qty的要求,您需要序列化MealRecipe模型和Item模型。
还为MealRecipe模型中的项目提供相关名称
class MealRecipe(models.Model):
meal = models.ForeignKey(Meal)
item = models.ForeignKey(Item,related_name='qty')
qty = models.IntegerField()
你的序列化工具将是
class MealRecipeSerializer(serializers.ModelSerializer):
class Meta:
model = MealRecipe
fields = ('qty')
class ItemSerializer(serializers.ModelSerializer):
qty = MealRecipeSerializer()
class Meta:
model = Item
fields = ('id','name','qty')
此外,如果您将查询集传递给序列化程序,请执行MealRecipeSerializer(many=True)