如果我听起来很困惑,那是因为我很困惑。我不熟悉django rest框架,我正在尝试创建一个相对简单的Recipe Management应用程序,该应用程序允许您自动创建购物清单。
动机:我知道可能不需要DRF,我可以使用django,但这个应用程序的重点是学习如何使用DRF。我们的目标是用DRF创造一个背部,然后用前部框架做一些花哨的恶作剧。
问题:我有一个Recipe
模型,它包含Ingredient
到RecipeIngredient
的ManyToMany
字段。我有点困惑于我应该如何处理RecipeSerializer
。到目前为止,它看起来是这样的:
class RecipeSerializer(serializers.ModelSerializer):
class Meta:
model = Recipe
fields = ('id','name','ingredients','tags','prep_time','cook_time', 'servings', 'instructions')
但我觉得,每当我想创建一个Recipe时,我都必须发出一个post请求来创建Ingredients
(如果它们还不存在的话(,一个请求创建Instructions
,一个创建Recipe
,一个生成RecipeIngredients
。
问题:是否有方法提出一个包含配方和所有子字段(配料、配方、说明(的请求,并创建所有实体?这将由RecipeSerializer
的create
函数来处理。
型号:
class Tag(models.Model):
name = models.CharField(max_length=100, unique=True)
class Ingredient(models.Model):
name = models.CharField(max_length=100, unique=True)
class Recipe(models.Model):
name = models.CharField(max_length=100)
ingredients = models.ManyToManyField(Ingredient,through='RecipeIngredient')
tags = models.ManyToManyField(Tag, related_name='recipes')
prep_time = models.PositiveIntegerField()
cook_time = models.PositiveIntegerField()
servings = models.PositiveIntegerField()
class Instruction(models.Model):
number = models.PositiveIntegerField()
text = models.TextField()
recipe = models.ForeignKey(Recipe, related_name='instructions', on_delete = models.CASCADE)
class RecipeIngredient(models.Model):
ingredient = models.ForeignKey(Ingredient, on_delete = models.CASCADE)
recipe = models.ForeignKey(Recipe, on_delete = models.CASCADE)
quantity = models.PositiveIntegerField()
unit = models.CharField(max_length=30, null= False, blank=True)
序列化程序:
class TagSerializer(serializers.ModelSerializer):
recipes = serializers.PrimaryKeyRelatedField(queryset = Recipe.objects.all(), many = True)
class Meta:
model = Tag
fields = ('id','name', 'recipes')
class InstructionSerializer(serializers.ModelSerializer):
class Meta:
model = Instruction
fields = ('id','number','text','recipe')
class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredient
fields = ('id','name')
class RecipeIngredientSerializer(serializers.ModelSerializer):
class Meta:
model = RecipeIngredient
fields = ('id','ingredient','recipe','quantity','unit')
class RecipeSerializer(serializers.ModelSerializer):
class Meta:
model = Recipe
fields = ('id','name','ingredients','tags','prep_time','cook_time', 'servings', 'instructions')
您可以使用嵌套的序列化程序,您可以按以下更改RecipeSerializer
class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredient
fields = '__all__'
class RecipeSerializer(serializers.ModelSerializer):
ingredients = IngredientSerializer(many=True)
class Meta:
model = Recipe
fields = ('id','name','ingredients','tags','prep_time','cook_time', 'servings', 'instructions')