如何从序列化器中的其他模型访问外键字段

时间:2019-11-08 13:41:34

标签: python django-models django-rest-framework django-views django-serializer

我正在尝试从序列化器中的另一个模型访问某些字段,但是我无法以任何方式使其工作。这就是我要怎么做。 这是我的模特:

class ContactSerializer(serializers.ModelSerializer):

    country_name = serializers.CharField(source='country.name')
    category_name = serializers.CharField(source='category.name')
    user_name = serializers.CharField(source='user.email')
    integration_name = serializers.CharField(source='integration.name')

    class Meta:
        model = Contact
        fields = ('first_name', 'last_name', 'address', 'city', 'country_name', 'email', 'phone',
                  'category_name', 'user_name', 'integration_name', 'job', )

这是我的序列化器

{
            "first_name": "First name",
            "last_name": "Last name",
            "address": "Address",
            "city": "City",
            "country_name": "Gabon",
            "email": "saidsadiasida@gmam.com",
            "phone": "0712345678",
            "category_name": "TestCategory",
            "user_name": "ekartdragos@cyberaxo.com",
            "integration_name": "testmonth",
            "job": [
                4
            ]
        }

如何在此序列化程序中的ContactCompany模型中访问公司字段?

这是API响应的样子

irb -r ./path_to_directory/pcset.rb

如何显示作业文本而不是ID?

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是使用serializerMethodField并获取您的需求信息。

class ContactSerializer(serializers.ModelSerializer):

    country_name = serializers.CharField(source='country.name')
    category_name = serializers.CharField(source='category.name')
    user_name = serializers.CharField(source='user.email')
    integration_name = serializers.CharField(source='integration.name')
    company = serializers.SerializerMethodField()

    class Meta:
        model = Contact
        fields = ('first_name', 'last_name', 'address', 'city', 'country_name', 'email', 'phone',
                  'category_name', 'user_name', 'integration_name', 'job', 'company' )
    def get_company(self, obj): 
    """
    at first we get the instance of ContactCompany from the id of object. then get the company information 
    """
        try:
            contact_company = ContactCompany.objects.get(contact=obj.id)
        expect ContactCompany.DoesNotExist: 
            # return or raise your desire this 

        return contact_company.company # here we have company id of this contact, also we can generate all company information from this.