项目中有一点复杂的模型。三个模型通过通用关系相互绑定。
以下是示例模型:
class Person(models.Model):
first_name = models.CharField()
last_name = models.CharField()
ptype = models.CharField()
mapping = models.ForeignKey("Mapping", related_name="mapping")
class Profile(models.Model):
rank = models.CharField()
company = models.ForeingKey("Company")
class Company(models.Model:
name = models.Charfield()
class Mapping(models.Model):
origin_person_ctype = models.ForeignKey(ContentType, related_name="origin_mapping")
origin_person_id = models.PositiveIntegerField()
origin_person_object = GenericForeignKey('origin_person_ctype', 'origin_person_id')
mapped_profile_ctype = models.ForeignKey(ContentType, related_name="mapped_mapping")
mapped_profile_id = models.PositiveIntegerField()
mapped_profile_object = GenericForeignKey('mapped_profile_ctype', 'mapped_profile_id')
company = models.ForeignKey("Company")
还有一个用于从 Person 模型中获取数据的 Rest API。
class PersonAPIView(generics.RetrieveUpdateAPIView):
serializer_class = PersonSerializer
lookup_url_kwarg = 'person_id'
def get_queryset(self):
return Person.objects.all().prefetch_related(
"mapping",
"mapping__mapped_profile_object",
"mapping__company"
)
class PersonSerializer(serializers.ModelSerializer)
class Meta:
model = Person
fields = (
'id',
'first_name',
'last_name',
'type',
)
现在,我必须在类中添加Company.name
和Profile.rank
作为嵌套字典列表PersonSerializer
。
我怎样才能像这样序列化通用关系值:
[
{"company1": "rank1"},
{"company2": "rank2"}
etc...
]