我的django模型(django版本1.7)具有以下结构
models.py
class Contact(models.Model):
email = models.CharField(verbose_name='Email', max_len=50)
class Person(Contact):
first_name = models.CharField(verbose_name='First Name', max_len=50)
last_name = models.CharField(verbose_name='Last Name', max_len=50)
class Company(Contact):
company_name = models.CharField(verbose_name='Company Name', max_len=50)
department = models.CharField(verbose_name='Department Name', max_len=50)
class Service(models.Model):
service_name = models.CharField(verbose_name='Service Name', max_len=50)
contact = models.ManyToManyField(Contact, verbose_name='Contact')
api / resources.py
class PersonResource(ModelResource):
class Meta:
queryset=Person.objects.all()
class CompanyResource(ModelResource):
class Meta:
queryset=Company.objects.all()
class ContactResource(ModelResource):
class Meta:
queryset=Contact.objects.all()
class ServiceResource(ModelResource):
class Meta:
queryset=Service.objects.all()
# fields
contact = fields.ToManyField(ContactResource, attribute='contact', full=True)
基于上述结构,我需要完全序列化Service,其中contact字段根据联系人的子类解析为正确的资源。我尝试使用dehydrate
方法执行此操作,但是它没有用。是否有其他方法可以实现这一目标,最好不使用其他软件包?
输出示例
{
'service_name': 'Helpdesk',
'contact': [
{
'first_name': 'John',
'last_name': 'Doe',
'email': 'jd@company.com'
},
{
'company_name': 'C.O.M.P.'
'department': 'technical',
'email': 'tech@comp.com'
}
]
}
谢谢