gpt4 book ai didi

python - Django REST框架: deserializing foreign key fails (many-to-many)

转载 作者:行者123 更新时间:2023-12-02 12:19:51 25 4
gpt4 key购买 nike

我有以下模型:

模型.py:

class Host(models.Model):
serialnr = models.IntegerField(primary_key=True)
...some other fields...

class Event(models.Model):
id = models.AutoField(primary_key=True)
hosts = models.ManyToManyField(Host, through='EventHost')
...some other fields...

class EventHost(models.Model):
serialnr = models.ForeignKey(Host, on_delete=models.PROTECT)
event = models.ForeignKey(Event, on_delete=models.CASCADE)
...some other fields...
class Meta:
unique_together = ("serialnr", "event")

序列化器.py:

class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = '__all__'

class HostSerializer(serializers.ModelSerializer):
class Meta:
model = Host
fields = '__all__'

class EventHostSerializer(serializers.ModelSerializer):
event = EventSerializer(read_only=True)
serialnr = HostSerializer(read_only=True)

class Meta:
model = EventHost
fields = '__all__'

View .py

class EventViewSet(viewsets.ModelViewSet):
queryset = Event.objects.order_by('-date')
serializer_class = EventSerializer

class HostViewSet(viewsets.ModelViewSet):
queryset = Host.objects.order_by('-serialnr')
serializer_class = HostSerializer

class EventHostViewSet(viewsets.ModelViewSet):
queryset = EventHost.objects.order_by('-start_date')
serializer_class = EventHostSerializer

我使用 HTTP POST 发送以下 JSON:

{event: {id: 4}, serialnr: {serialnr: 1234}, other_filed: 20} 

但它不是 event_id 和 serialnr_id 没有反序列化,如日志中所示:

psycopg2.errors.NotNullViolation: null value in column "event_id" violates not-null constraint
DETAIL: Failing row contains (12, 20, null, null).

我可以使用 HTTP GET 读取数据,但无法使用 POST 写入数据。我应该如何构建正确的序列化器才能使其工作?

此外,当我尝试发送如下 JSON 时,它失败了:

{event_id: 4, serialnr_id: 1234, other_filed: 20} 

最佳答案

由于 eventserialinrEventHost 上的外键,因此您需要发送已存在的数据,因此我建议使用 PrimaryKeyRelatedField 通过这种方式,如果您发送数据库中不存在的 ID,您就会得到验证。

您需要发送如下数据:{事件:4,serialnr:1234,other_filed:20}

并将序列化器更改为:

from rest_framework.relations import PrimaryKeyRelatedField


class EventHostSerializer(serializers.ModelSerializer):
event = PrimaryKeyRelatedField(queryset=Event.objects.all())
serialnr = PrimaryKeyRelatedField(queryset=Host.objects.all())

class Meta:
model = EventHost
fields = '__all__'

# add this(if needed) to get event/serialnr representation instead of primary keys
# might be usefull for you when you retrieve the object back (in list/retrieve operations)
def to_representation(self, instance):
ret = super().to_representation(instance)
ret['event'] = EventSerializer(context=self.context).to_representation(instance.event)
ret['serialnr'] = HostSerializer(context=self.context).to_representation(instance.serialnr)
return ret

稍后编辑:

我发现有一个名为 django-extra-fields 的库可以更好地完成此操作。

https://github.com/Hipo/drf-extra-fields#presentableprimarykeyrelatedfield

from drf_extra_fields.relations import PresentablePrimaryKeyRelatedField


class EventHostSerializer(serializers.ModelSerializer):
event = PresentablePrimaryKeyRelatedField(
queryset=Event.objects.all(), presentation_serializer=EventSerializer
)
serialnr = PresentablePrimaryKeyRelatedField(
queryset=Host.objects.all(), presentation_serializer=HostSerializer
)

class Meta:
model = EventHost
fields = '__all__'

关于python - Django REST框架: deserializing foreign key fails (many-to-many),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60091148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com