我的模型是Purchase,Item,ItemGroup,Store
这些是模型的相关字段:
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()
我想为购买编写一个序列化器。 对于每次购买,我需要以下输出:
{"item": "item_name", "store": "store_name"}
(也有一些其他的Purcahse字段,但是很容易获取)。
我尝试使用django双下划线__
样式跟踪关系,但这不起作用:
class PurchaseSerializer(serializers.ModelSerializer):
class Meta:
model = Purchase
fields = ('item', 'item__group__store')
答案 0 :(得分:1)
class PurchaseSerializer(serializers.ModelSerializer):
store = serializers.CharField(source="item.group.store.name")
class Meta:
model = Purchase
fields = ('item', 'store')
记住要预取存储以优化请求。
答案 1 :(得分:1)
使用source
自变量
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')