Quantcast
Viewing latest article 14
Browse Latest Browse All 45

How to Serialize with field from reverse related model - Django rest framework

I have an api that retrieves all items related to a project through a manytomany model with an extra order field. I am now trying to serialize the items with the order value on it.

One solution would be to serialize the through model, but that gives a result like this:

{
    "order": 1,
    "item": {
        "id": 3031,
        "name": "Miami"
    }
},

I would like to serialize the item instead and get an output like so:

{
    "order": 1,
    "id": 3031,
    "name": "Miami"
}

I can't add the order as an Attribute to the item model, as it's a manytomany field. Or I guess I could but would have to take the first object of a list, which is not a solution I think is very clean and would probably add a separate database call.

All the items are fetch like so:

ProjectItem.objects.filter(project_id=self.kwargs['project_pk']).select_related('item')

Any ideas?


Viewing latest article 14
Browse Latest Browse All 45

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>