我試圖從Django Rest Framework返回一個HttpResponse,其中包括來自2個鏈接模型的數據。 型號有:Django Rest框架 - 在串行器中獲取相關模型字段
class Wine(models.Model):
color = models.CharField(max_length=100, blank=True)
country = models.CharField(max_length=100, blank=True)
region = models.CharField(max_length=100, blank=True)
appellation = models.CharField(max_length=100, blank=True)
class Bottle(models.Model):
wine = models.ForeignKey(Wine, null=False)
user = models.ForeignKey(User, null=False, related_name='bottles')
我想擁有的瓶型,其中包括從葡萄酒相關信息的串行器。
我想:
class BottleSerializer(serializers.HyperlinkedModelSerializer):
wine = serializers.RelatedField(source='wine')
class Meta:
model = Bottle
fields = ('url', 'wine.color', 'wine.country', 'user', 'date_rated', 'rating', 'comment', 'get_more')
不工作。
任何想法,我可以做到這一點?
謝謝:)
感謝這個,我幾乎沒有。 @ tom-christie解釋瞭如何獲取對象本身,但我無法從Wine對象中獲取所有字段。 – bpipat
嘗試將'source ='*''作爲'RelatedField'參數。 – mariodev
我仍然在查詢結果中獲得unicode名稱。嘗試wine.color在字段中不起作用 source ='*'會發生什麼變化? – bpipat