How to include a field from the joining table in the queryset?

Viewed 1857

We have Django Rest Framework at work, however I'm a front-end developer who's decided to do a little bit of DRF for his next open-source project.

I don't wish to copy-paste a lot of code, as you can see all of my serializers, models, etc... on GitHub.

I've asked the developers at work. One said I should override to_representation which doesn't seem right, as we're building the serialized model from scratch. Whereas the other Django developer at work suggested I look into custom relation fields.

Essentially given the following serializer, how would I include the "type" (badly named) column from my joining table in my queryset:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'countries')

In pseudo-code I'm looking for something like the following, so when you get a user, you also get associated countries, which is working just fine via the many-to-many relationship, as well as the "type" from the joining table:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'countries', 'pinned.type')

I'd expect a JSON response of something like the following:

{
    "username": "wildhoney",
    "countries": [
        { "country_id": 4, "type": 1 },
        { "country_id": 5, "type": 2 },
        { "country_id": 6, "type": 3 }
    ]
}

At the moment I only receive a list of country_ids.

1 Answers
Related