【发布时间】:2021-02-21 14:55:50
【问题描述】:
目前我尝试从我的 API 获取食谱。我有一个包含两个表的数据库,其中一个包含食谱及其 ID,但没有成分,另一个表包含成分和食谱 ID。现在我找不到API“组合”这些的方法。也许是因为我在我的成分模型中添加了相关名称的配方 ID,但我必须这样做,否则会发生此错误:
ERRORS:
recipes.Ingredients.recipeid: (fields.E303) Reverse query name for 'Ingredients.recipeid' clashes with field name 'Recipe.ingredients'.
HINT: Rename field 'Recipe.ingredients', or add/change a related_name argument to the definition for field 'Ingredients.recipeid'.
型号
from django.db import models
class Ingredients(models.Model):
ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True)
recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='recipeid', blank=True, null=True, related_name='+')
amount = models.CharField(blank=True, null=True, max_length=100)
unit = models.CharField(blank=True, null=True, max_length=100)
unit2 = models.CharField(blank=True, null=True, max_length=100)
ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255)
class Meta:
managed = True
db_table = 'Ingredients'
class Recipe(models.Model):
recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase.
title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase.
preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase.
images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase.
#ingredients = models.ManyToManyField(Ingredients)
ingredients = models.ManyToManyField(Ingredients, related_name='recipes')
class Meta:
managed = True
db_table = 'Recipes'
如果没有问题,则必须在序列化程序或视图中。
序列化器
class IngredientsSerializer(serializers.ModelSerializer):
# ingredients = serializers.CharField(source='ingredients__ingredients')
class Meta:
model = Ingredients
fields = ['ingredient','recipeid']
class FullRecipeSerializer(serializers.ModelSerializer):
ingredients = IngredientsSerializer(many=True)
class Meta:
model = Recipe
fields = ['title','ingredients']
查看
class FullRecipesView(generics.ListCreateAPIView):
serializer_class = FullRecipeSerializer
permission_classes = [
permissions.AllowAny
]
queryset = Recipe.objects.all()
This is at the moment my output 但我想要例如id 为 0 的配方和所有配方 id 为 0 的成分。 我真的希望你能帮助我。非常感谢!
【问题讨论】:
-
你有什么错误吗?
-
有几件事:您本可以按照提示进行操作,而不是做任何您认为正确的事情。如果您不理解提示,请查看 Django 文档。其次,您将配方模型标记为托管,而您的成分模型未托管。这是故意的吗?我假设它们都是不受管理的,这就引出了为什么使用 Django 的问题?最后,要回答您关于 JSON 可序列化的问题,请查看 Django Rest Framework documentation。
-
@Bobort 我多次阅读文档,但文档只是有一个多对多的示例,其中包含他们正在填充的数据库。我的数据库已经填满,我正在寻找一种“组合”数据的方法。
-
目前我不知道问题出在哪里,我只想知道它是在模型中还是在 API 本身中,因此,我尝试更改不同的值我不是 100% 确定他们是否正确。
标签: python python-3.x django django-models django-rest-framework