0
すでにこのエラーについて言及している質問がいくつかありますが、いずれの回答も見つけられませんでした。多対多のフィールドを持つオブジェクトを作成するDjangoエラー
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)
01シリアライザ同じエラーでPOSTリクエスト結果に
venues
に2つの会場オブジェクトのリストを渡す
要求
c = Client()
data = {
'start_datetime': now,
}
response = c.post('/matches/findmatch/', data)
。
お返事ありがとうございました。今は試してみることはできませんが、私が見逃していたようです。 –