如何同时保存ForeignKey对象及其父对象

问题描述 投票:-1回答:1

Angular 8,Django3。我有两个模型RecipeIngredients。我在前端使用ngModels将数据发送到Django,以创建Recipe模型。当您单击“提交”时,在一页上,所有RecipeIngredients数据都发送到后端。

根据我对ManyToOne关系的了解,models.ForeignKey应该在属于“许多”的模型上进行。因此,每个Ingredients有“很多” Recipe,所以我在Foreignkey上有Ingredients

我的问题是,当我将所有这些数据发送给Django时,由于Ingredients上没有ingredients字段,因此未创建RecipeSerializer

models.py

class Recipe(models.Model):
    name = models.CharField(max_length=30)


class Ingredients(models.Model):
    name = models.CharField(max_length=50)
    recipe = models.ForeignKey(Recipe, related_name='ingredients', on_delete=models.CASCADE)

views.py

class AddRecipe(generics.CreateAPIView):
    serializer_class = RecipeFullSerializer

serializers.py

class IngredientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ingredients
        fields = ['name']

class RecipeFullSerializer(serializers.ModelSerializer):
    ingredients = IngredientSerializer(many=True, read_only=True)
    class Meta:
        model = Recipe
        fields = ['name', 'ingredients']

样本数据

ingredients: Array(1)
0: {name: "23"}
length: 1
__proto__: Array(0)
name: "23"

我正在后端获取Ingredients数据的数组,只是不确定如何使用外键将所有数据同时保存到Recipes。我想我可以创建一个自定义视图来为我完成所有这些工作,但是我认为会有一个基于类的视图可以做到这一点。

请求

DATA = {str} 'Traceback (most recent call last):\n  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_resolver.py", line 178, in _getPyDictionary\n    attr = getattr(var, n)\n  File "/Users////
FILES = {MultiValueDict: 0} <MultiValueDict: {}>
POST = {QueryDict: 0} <QueryDict: {}>
QUERY_PARAMS = {str} 'Traceback (most recent call last):\n  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_resolver.py", line 178, in _getPyDictionary\n    attr = getattr(var, n)\n  File "/Users////
accepted_media_type = {str} 'application/json'
accepted_renderer = {JSONRenderer} <rest_framework.renderers.JSONRenderer object at 0x10d16d550>
auth = {Token} 75692a2c41b066795dd719fe1d4b1de94f10980f
authenticators = {list: 4} [<rest_framework_jwt.authentication.JSONWebTokenAuthentication object at 0x10d149940>, <rest_framework.authentication.SessionAuthentication object at 0x10d1495c0>, <rest_framework.authentication.BasicAuthentication object at 0x10d149208>, <rest_framework.authentication.TokenAuthentication object at 0x10d149ef0>]
content_type = {str} 'application/json'
data = {dict: 7} {'restaurant': '2', 'name': 'test', 'cook_time': '10', 'servings': '10', 'calories': '10', 'price': 10, 'ingredients': [{'amount': '10', 'unit': 'lb', 'name': 'food'}]}
 'restaurant' = {str} '2'
 'name' = {str} 'test'
 'cook_time' = {str} '10'
 'servings' = {str} '10'
 'calories' = {str} '10'
 'price' = {int} 10
 'ingredients' = {list: 1} [{'amount': '10', 'unit': 'lb', 'name': 'food'}]
  0 = {dict: 3} {'amount': '10', 'unit': 'lb', 'name': 'food'}
  __len__ = {int} 1
 __len__ = {int} 7
negotiator = {DefaultContentNegotiation} <rest_framework.negotiation.DefaultContentNegotiation object at 0x10d07cef0>
parser_context = {dict: 5} {'view': <users.views.AddRecipe object at 0x10d07c780>, 'args': (), 'kwargs': {}, 'request': <rest_framework.request.Request object at 0x10d149080>, 'encoding': 'utf-8'}
parsers = {list: 3} [<rest_framework.parsers.JSONParser object at 0x10d1494a8>, <rest_framework.parsers.FormParser object at 0x10d1494e0>, <rest_framework.parsers.MultiPartParser object at 0x10d149b00>]
query_params = {QueryDict: 0} <QueryDict: {}>
stream = {WSGIRequest} <WSGIRequest: POST '/users/addrecipe'>
successful_authenticator = {TokenAuthentication} <rest_framework.authentication.TokenAuthentication object at 0x10d149ef0>
user = {CustomUser} user
version = {NoneType} None
versioning_scheme = {NoneType} None
django django-rest-framework many-to-one
1个回答
0
投票

您将成分设置为read_only,因此不会创建它们。如果要保存它们,则需要删除它:

class RecipeFullSerializer(serializers.ModelSerializer):
    ingredients = IngredientSerializer(many=True)
    class Meta:
        model = Recipe
        fields = ['name', 'ingredients']
© www.soinside.com 2019 - 2024. All rights reserved.