Django序列化器未显示子模型字段

时间:2019-11-28 14:50:09

标签: python django django-rest-framework

我在使用序列化器在另一个序列化器(外键关系)中使用模型序列化器时,序列化器无法从子模型返回字段时遇到问题。我不是在寻找解决方案,而是为什么它不起作用。

models.py

class LinkedinAccount(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    is_prospect = models.BooleanField(default=False)

class LinkedinProspectAccount(LinkedinAccount):
    title = models.CharField(max_length=255, blank=True)
    company = models.CharField(max_length=100, blank=True)
    country = models.CharField(max_length=255, blank=True)
    city = models.CharField(max_length=255, blank=True)

serializers.py

class LinkedinAccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = user_account.models.LinkedinAccount
        fields = ('id', 'name')
        read_only_fields = ('date_created',)


class LinkedinProspectAccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = user_account.models.LinkedinProspectAccount
        fields = ('title', 'company', 'country', 'city')
        read_only_fields = ('date_created',)


class ConversationSerializer(serializers.ModelSerializer):
    linkedin_account = user_account.serializers.LinkedinAccountSerializer()
    last_message = MessageSerializer()
    prospect = user_account.serializers.LinkedinProspectAccountSerializer()

    class Meta:
        model = conversation.models.Conversation
        fields = ('id', 'linkedin_account', 'prospect', 'conversation_id', 'archived',
                  'last_message')
        lookup_field = None

    read_only_fields = ('created_at', 'updated_at',)

我从使用generics.ListCreateAPIView的普通GET请求获得的信息是:

  

[OrderedDict([('id',1),('linkedin_account',OrderedDict([('id',1),   ('name','Test LinkedIn account')])),('prospect',OrderedDict()),   ('conversation_id','100'),('archived',False),('last_message',   无)])]

潜在客户对象没有字段,如果我在序列化器中添加基本模型字段,则返回它们,但仍然没有子模型字段。单独使用LinkedinProspectAccountSerializer时,它可以正常工作。目前,我正在使用它作为解决方法:

def get_prospect(self, obj):
    prospect = user_account.models.LinkedinProspectAccount.objects.get(id=obj.prospect.id)
    serializer = user_account.serializers.LinkedinProspectAccountSerializer(prospect)
    return serializer.data

0 个答案:

没有答案