【问题标题】:Django Rest API ManyToMany gives nothing [] in APIDjango Rest API ManyToMany 在 API 中没有给出任何 []
【发布时间】: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


【解决方案1】:

来自ForeignKey.related_name的文档,

如果您不希望 Django 创建反向关系,请将 related_name 设置为 '+' 或以 '+' 结束。

因此,将 Ingredients.recipeid 字段的 related_name 更改为

class Ingredients(models.Model):
    # rest of the fields
    recipeid = models.ForeignKey(
        'Recipe',
        models.DO_NOTHING,
        db_column='recipeid',
        blank=True,
        null=True,
        related_name="ingredients_ref" # Changed the related name 
    )

然后,使用python manage.py makemigrationspython manage.py migrate 迁移数据库

然后,将您的 FullRecipeSerializer 类更新为,

class FullRecipeSerializer(serializers.ModelSerializer):
    ingredients_forward = IngredientsSerializer(many=True, source="ingredients")
    ingredients_backward = IngredientsSerializer(many=True, source="ingredients_ref")

    class Meta:
        model = Recipe
        fields = ['title', 'ingredients_forward', 'ingredients_backward']

请注意,这里我添加了两个名为ingredients_forwardingredients_backward 的字段,因为RecipeIngredients 之间存在两种类型的关系,我不确定您要查找的是哪一种。

【讨论】:

  • 谢谢它有效。但是我是否理解正确,我需要将配料倒过来才能从食谱中获取配料?以及如何使用前向成分?
  • 根据您的模型结构在您的情况下两者都不同。我想知道为什么你首先需要Ingredients.recipeid
  • 我不确定你的意思。我需要配方 ID,因为它是配方的唯一参考
  • 好的,那现在有什么问题?
  • 我只是想了解forward和backward的成分是什么。
猜你喜欢
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 2021-05-07
  • 2017-02-02
  • 2018-07-08
  • 1970-01-01
相关资源
最近更新 更多