0
可以說我有車型像這樣:如何自定義django模型對象的嵌套序列化列表,使其成爲鍵/值對?
class Device(models.Model):
name = models.CharField(max_length=100,null=True)
model = models.CharField(max_length=100,null=True)
lab = models.ForeignKey(Lab,null=True, related_name='devices')
class Lab(models.Model):
name = models.CharField(max_length=100)
當一個實驗室可以有多個設備。 當我創建串行我能夠得到的東西回來這樣的:
{'name':'My Lab','devices':[{'name':'Device 1','model':'iPhone'},{'name':'Device 2','model':'iPad'}]}
不過,我想回去是鍵/值對,而不是設備的列表,像這樣:
{'name':'My Lab','devices':{'Device 1':{'model':'iPhone'},'Device 2':{'model':'iPad'}}}
我在想像我必須使用SerializerMethodField
來完成這項工作,但是我很難解決這個問題。
我想,這就是去了解它的最佳方式。我質疑這個用例,但如果這是你需要的,那麼這就是它的方法。 –
謝謝。就使用情況而言,我無法在O(1)時間內從實驗室獲取任何設備的信息。 – user2301357