1

My models are Purchase, Item, ItemGroup, Store

These are the relevant fields of the models:

class Store(models.Model):
    name = models.CharField(max_length=100)

class ItemGroup(models.Model):
    name = models.CharField(max_length=100)
    store = models.ForeignKey(Store)

class Item(models.Model):
    name = models.CharField(max_length=100)
    group = models.ForeignKey(ItemGroup)

class Purchase(models.Model):
    item = models.ForeignKey(Item)
    date = models.DateTimeField()

I want to write a serializer for Purchase. For each purchase, I want the following output:

{"item": "item_name", "store": "store_name"}

(Also there are some additional Purcahse fields, but these are easy to fetch).

I've tried to follow the relations using the django double underscore __ style, but this does not work:

class PurchaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Purchase
        fields = ('item', 'item__group__store')

2 Answers 2

2
class PurchaseSerializer(serializers.ModelSerializer):
    store = serializers.CharField(source="item.group.store.name")
    class Meta:
        model = Purchase
        fields = ('item', 'store')

Remember to prefetch store for requests optimization.

Sign up to request clarification or add additional context in comments.

Comments

1

Use source argument

class PurchaseSerializer(serializers.ModelSerializer):
    item = serializers.CharField(source='item.name')
    store = serializers.CharField(source="item.group.store.name")

    class Meta:
        model = Purchase
        fields = ('item', 'store')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.