Django API ManyToMany对现有数据库不起作用



目前我正试图从我的API中获取食谱。我有一个数据库,有两个表,一个是配方和它们的id,但没有成分,另一个表包含成分和配方id;组合";那些也许是因为我在配方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 = False
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()

这是我目前的输出但我想要例如id为0的配方和所有id为0配方的配料。我真的希望你能帮助我。非常感谢!

ingredients重命名为FullRecipeSerializer中的其他名称。它与Recipe模型中的ingredients冲突。这应该能解决你的问题。例如

class FullRecipeSerializer(serializers.ModelSerializer):
ingredients_recipe = IngredientsSerializer(many=True, source= 'ingredientid')
class Meta:
model = Recipe
fields = ['title','ingredients_recipe']

最新更新