DRF只读字段仍然有效

时间:2019-02-01 16:28:26

标签: python django django-rest-framework

我有一个字段,希望一直成为用户。我的序列化器是这样的:

projects_for_template = (
      db.session.query(Project.id,Project.client_name,func.count(Entry.id).label('entry_count'))
      .join(Entry, Project.name == Entry.project)
      .group_by(Project.id,Project.client_name) # add all the fields here
)

但是它给了我错误class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' read_only_fields = ('user',) def perform_save(self, serializer): serializer.save(user=self.request.user) class MyModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... ,但是该字段是只读的……我不明白。

1 个答案:

答案 0 :(得分:0)

首先,没有用于序列化器的名为 perform_save() 的方法,用于 viewset 类。这可能是问题
使用如下的 save() 方法

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'
        read_only_fields = ('user',)

    def save(self, **kwargs):
        kwargs['user'] = self.context['request'].user
        return super().save(**kwargs)