gpt4 book ai didi

Django Rest Framework如何根据ID保存带有相关字段的模型

转载 作者:行者123 更新时间:2023-12-04 04:48:53 32 4
gpt4 key购买 nike

我对 DRF 有点陌生。我有看起来像这样的记录模型:

class Records(models.Model):
owner = models.ForeignKey(User, null=True)
activity = models.ForeignKey(Activity, null=True)
time_start = models.DateTimeField(null=True)
time_end = models.DateTimeField(null=True)

...

RecordSerializer 是这样的:
class RecordSerializer(serializers.ModelSerializer):

now = datetime.today()
owner = serializers.Field(source='owner.username')
time_start = serializers.DateTimeField(source='now')

class Meta:
model = Records
fields = ("owner", "activity", "time_start")

这是观点:
class StartApiView(generics.CreateAPIView):
model = Records
serializer_class = RecordSerializer

def pre_save(self, obj):
obj.owner = self.request.user

POST 请求是从 Backbone 发送的,它包含一个带有事件 ID 的字段,例如“{activity:12}”。如果想让view保存Record,将activity设置为id为12的Activity怎么办?

最佳答案

Django REST 框架 provides a PrimaryKeyRelatedField 对于这个用例。

class RecordSerializer(serializers.ModelSerializer):
activity = serializers.PrimaryKeyRelatedField()
owner = serializers.CharField(read_only=True, source='owner.username')
time_start = serializers.DateTimeField(source='now')

class Meta:
model = Records
fields = ("owner", "activity", "time_start")

这将产生与您正在寻找的类似的输出,并且它将接受 id想要更新它时的事件。

关于Django Rest Framework如何根据ID保存带有相关字段的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27028832/

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