Django REST Framework: Add field from related obje

2019-08-04 11:56发布

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.

0条回答
登录 后发表回答