Django错误创建具有多对多字段的对象

时间:2017-12-04 02:13:38

标签: django django-models

有几个问题已经提到这个错误,但我找不到任何答案。

  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
  File "/home/joao/Code/projects/courty/courty-django/apps/matching/serializers.py", line 19, in create
return MatchFinder.objects.create(**validated_data)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/query.py", line 392, in create
obj = self.model(**kwargs)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/base.py", line 568, in __init__
_setattr(self, prop, kwargs[prop])
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 536, in __set__
manager = self.__get__(instance)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__
return self.related_manager_cls(instance)
  File "/home/joao/.virtualenvs/courty/lib64/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__
(instance, self.pk_field_names[self.source_field_name]))
 ValueError: "<MatchFinder: MatchFinder object>" needs to have a value for field "id" before this many-to-many relationship can be used.

模型

class MatchFinder(models.Model):
    player = models.ForeignKey(Player)
    start_datetime = models.DateTimeField(null=False)
    venues = models.ManyToManyField(Venue, help_text='Pitches preferred by this player', blank=True)

查看

class MatchFinderView(views.APIView):

    def post(self, request, format=None):
        serializer = MatchFinderSerialzer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

串行

class MatchFinderSerialzer(BaseModelSerializer):

    class Meta:
        model = MatchFinder
        fields = ('start_datetime', 'venues')

    def create(self, validated_data):
        return MatchFinder.objects.create(**validated_data)

请求

 c = Client()
 data = {
        'start_datetime': now,
        }
 response = c.post('/matches/findmatch/', data)

在帖子请求的venues中传递2个Venue对象的列表会导致相同的错误。

1 个答案:

答案 0 :(得分:1)

有多个问题,

首先,&#39;播放器&#39;是一个不可为空的字段 - 所以你需要在字段中添加它。

其次,对于嵌套关系,您需要明确指定应如何保存子关系。我相应地修改了Serializer,

class MatchFinderSerialzer(BaseModelSerializer):

     class Meta:
         model = MatchFinder
         fields = ('player', 'start_datetime', 'venues')

     def create(self, validated_data):
         venues_data = validated_data.pop('venues')
         match_finder = MatchFinder.objects.create(**validated_data)
         for venue_data in venues_data:
             Venue.objects.create(match_finder=match_finder, **venue_data)
         return match_finder

同时确保您提供“玩家ID”。在你的帖子请求中。