Django Rest Framework如何根据ID保存带有相关字段的模型 [英] Django Rest Framework how to save a model with Related Field based on ID

查看:23
本文介绍了Django Rest Framework如何根据ID保存带有相关字段的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 DRF 有点陌生.我的 Record 模型如下所示:

I'm kind of new to DRF. I have Record model that looks like this:

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 就是这个:

The RecordSerializer is this one:

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怎么办?

The POST request is sent from Backbone and it includes a field with the activity id, for example "{activity:12}". What should I do if I want the view to save the Record and set the activity to the Activity with the id of 12?

推荐答案

Django REST Framework 为这个用例提供了一个 PrimaryKeyRelatedField.

Django REST Framework provides a PrimaryKeyRelatedField for exactly this use case.

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.

This will produce output similar to what you are looking for, and it will accept the id of the activity when you want to update it.

这篇关于Django Rest Framework如何根据ID保存带有相关字段的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆