【发布时间】:2016-03-08 12:35:40
【问题描述】:
我在使用 DRF3 中的 through 参数序列化多对多关系时遇到了一些问题
基本上我有食谱和成分,通过一个中间模型组合起来,该模型指定特定成分的使用量和单位。
这些是我的模型:
from django.db import models
from dry_rest_permissions.generics import authenticated_users, allow_staff_or_superuser
from core.models import Tag, NutritionalValue
from usersettings.models import Profile
class IngredientTag(models.Model):
label = models.CharField(max_length=255)
def __str__(self):
return self.label
class Ingredient(models.Model):
recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE)
ingredient_tag = models.ForeignKey(IngredientTag, on_delete=models.CASCADE)
amount = models.FloatField()
unit = models.CharField(max_length=255)
class RecipeNutrition(models.Model):
nutritional_value = models.ForeignKey(NutritionalValue, on_delete=models.CASCADE)
recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE)
amount = models.FloatField()
class Recipe(models.Model):
name = models.CharField(max_length=255)
ingredients = models.ManyToManyField(IngredientTag, through=Ingredient)
tags = models.ManyToManyField(Tag, blank=True)
nutritions = models.ManyToManyField(NutritionalValue, through=RecipeNutrition)
owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True)
def __str__(self):
return self.name
这些是目前我的序列化程序:
from recipes.models import Recipe, IngredientTag, Ingredient
from rest_framework import serializers
class IngredientTagSerializer(serializers.ModelSerializer):
class Meta:
model = IngredientTag
fields = ('id', 'label')
class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredient
fields = ('amount', 'unit')
class RecipeSerializer(serializers.ModelSerializer):
class Meta:
model = Recipe
fields = ('id', 'url', 'name', 'ingredients', 'tags', 'nutritions', 'owner')
read_only_fields = ('owner',)
depth = 1
我已经在 SO 和网络上进行了相当多的搜索,但我无法弄清楚。如果有人能指出我正确的方向,那就太好了。
我可以像这样获取要返回的成分列表:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"url": "http://localhost:8000/recipes/1/",
"name": "Hallo recept",
"ingredients": [
{
"id": 1,
"label": "Koek"
}
],
"tags": [],
"nutritions": [],
"owner": null
}
]
}
但我想要的是金额和单位也可以退回!
【问题讨论】:
-
当
ManyToManyField设置为IngredientTag时,为什么您希望在成分中包含amount和unit? -
@AKS 我使用 through=Ingredient 设置了中间模型成分。基本上序列化现在发生在成分标签上,我希望它发生在成分上。我不确定会发生什么。我对 DRF 和 Django 有点陌生
-
请举例说明您在序列化后对
ingredients的期望? -
只是想知道,成分标签是什么?
-
@AKS 是的,对不起,我所期望的(ed)是我的答案中的输出,无论成分标签是嵌套的还是扁平的,对我来说都无关紧要!
标签: python django django-rest-framework