我是DRF的新手。我有Record模型,如下所示:
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}"。如果我希望视图保存记录并将活动设置为ID为12的活动,我该怎么办?
答案 0 :(得分:22)
接受的答案适用于DRF v2.x 但is no longer for newer (3.x) versions,因为它会引发此AssertionError
:
AssertionError:关系字段必须提供
queryset
参数,或设置read_only=True
。
对于较新版本,只需向其添加queryset
参数:
class RecordSerializer(serializers.ModelSerializer):
activity = serializers.PrimaryKeyRelatedField(queryset=Activity.objects.all())
// [...]
答案 1 :(得分:3)
Django REST Framework 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
。