嘗試從DRF中的中介模型訪問字段很困難。Django Rest框架中的中介模型的訪問字段
讓我們來看看相關的模型:
class School(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=50, verbose_name=_(u'Name'))
staff_order = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name=_(u'Staff ordering'), through='StaffOrder', related_name='school_staff_order')
class User(AbstractUser):
phone = models.CharField(max_length=20, blank=True, null=True)
address = models.CharField(max_length=150, blank=True, null=True)
about_me = models.CharField(max_length=200, blank=True, null=True)
REQUIRED_FIELDS = ['email']
def __unicode__(self):
return u'{0}'.format(self.username)
class StaffOrder(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
school = models.ForeignKey(School)
order = models.PositiveSmallIntegerField(default=0, verbose_name=_(u'Staff ordering for this school'))
class Meta:
verbose_name_plural = _(u'Staff ordering')
現在我很期待是能夠返回用戶一個QuerySet(StaffSerializer)當從StaffOrder閱讀順序字段。下面是串行器:
class StaffRoleSerializer(serializers.ModelSerializer):
class Meta:
model = StaffOrder
fields = (
'order',
)
class StaffSerializer(serializers.ModelSerializer):
username = serializers.CharField(max_length=75, required=True)
email = serializers.CharField(max_length=75, required=True)
order = StaffRoleSerializer(source='school_staff_order')
class Meta:
model = User
什麼是爲了使StaffSerializer返回是一個經理,而不是從與該用戶相關StaffOrder模型的順序領域。
爲員工一個JSON預期的響應將是這樣的:
[
{
"username": "Denise",
"email": "[email protected]",
"order": 9
},
{
"username": "Ina",
"email": "[email protected]",
"order": 4
}
]
我很樂意能寫也從串行此值,但我可以做的是,在視圖集,但我真的需要在串行器本身讀取這個值...任何想法我在這裏失蹤?
你的命名很混亂。爲什麼在訂單欄中有source = school_staff_order?它指的是什麼? –
@ zaphod100.10在序列化器中映射中間模型時,這似乎是一個要求。它映射到School.staff_order – AlejandroVK
中的相關名稱不應該在學校模型中將'staff_order'字段命名爲'users'或'staff'嗎?因爲它與用戶有很多關係。你能舉一個你想要的json的例子嗎? –