[英]Update foreign key in Django rest framework model using viewsets.ModelViewSet view
I am relatively new to DRF and having hard time updating the foreign key in my model via POST request.我对 DRF 比较陌生,并且很难通过POST请求更新我的 model 中的外键。
# Model for Event.
class Event(models.Model):
heading = models.TextField()
event_construction_site = models.ForeignKey(
ConstructionSite, on_delete=models.CASCADE, related_name='construction_site_events', null=True)
def __str__(self):
return str(self.id)
class ConstructionSiteShortSerializer(serializers.ModelSerializer):
class Meta:
model = ConstructionSite
fields = ['id']
# Serializer for Event.
class EventSerializer(serializers.ModelSerializer):
event_construction_site = ConstructionSiteShortSerializer()
event_posted_by = CustomUserSerializer()
class Meta:
model = Event
fields = ('id', 'heading', 'event_construction_site')
Structure of my GET
response is as follows:我的
GET
响应的结构如下:
{
id: 1,
heading: "Truck with formwork arrived",
event_construction_site: {
id: 3
}
}
My concern here is how can I update the id
of event_construction_site
?我关心的是如何更新
event_construction_site
的id
?
I tried updating it like as follows:我尝试如下更新它:
{
"heading": "a",
"event_construction_site": {"id": 2}
}
Dute to id
of event_construction_site
being nested field I get an error that says =>由于
event_construction_site
的id
是嵌套字段,我收到一个错误,上面写着 =>
The `.create()` method does not support writable nested fields by default.
You can use a PrimaryKeyRelatedField.您可以使用 PrimaryKeyRelatedField。
class EventSerializer(serializers.ModelSerializer):
event_construction_site = serializers.PrimaryKeyRelatedField(queryset=ConstructionSite.objects.all())
event_posted_by = CustomUserSerializer()
class Meta:
model = Event
fields = ('id', 'heading', 'event_construction_site')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.