Django REST Framework: Add field from related object to ModelSerializer

拟墨画扇 提交于 2019-12-11 11:09:10

问题


I'm trying to allow a field that belongs to a related object to be readable and writable from a ModelSerializer. I have a model Group:

class Group(models.Model):
    ...
    name = models.CharField(max_length=128)
    def get_language(self):
        line = self.line_set.all()[0]
        return line.language
    ...

and corresponding serializer:

class GroupSerializer(serializers.ModelSerializer):
    language = serializers.CharField(source='get_language')

    class Meta:
        model = Group
        fields = ('id', 'name', 'language')
        lookup_field= 'pk'

The Group model is related to the Line model, where the language field lives:

class Line(models.Model):
    ...
    language = models.CharField(max_length=24)
    groups = models.ManyToManyField(Group, blank=True, null=True)
    ...

I'm trying to expose Line.language in the Group API for reading and writing. I've tried using CharField as above, but when I go to post a new model, I get this error:

TypeError at /AO/s/v2/group/

'get_language' is an invalid keyword argument for this function

I also thought of trying a custom related field and implementing from_native, but that requires a queryset which isn't relevant here.

Thanks in advance.

来源:https://stackoverflow.com/questions/23822339/django-rest-framework-add-field-from-related-object-to-modelserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!