简体   繁体   English

如何从序列化程序中的另一个 model 访问外键字段

[英]How to access foreign key field from another model in serializer

I'm trying to access some fields from another model in my serializer but I can't get it working by any means.我正在尝试从我的序列化程序中的另一个 model 访问一些字段,但我无法通过任何方式让它工作。 Here is how I'm going about this.这就是我要解决的问题。 Here are my models:这是我的模型:

class Category(models.Model):
    name = models.CharField(max_length=256)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name


class Contact(models.Model):
    first_name = models.CharField(max_length=256)
    last_name = models.CharField(max_length=256)
    address = models.CharField(max_length=1024)
    city = models.CharField(max_length=256)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    email = models.EmailField(max_length=256, unique=True)
    phone = models.CharField(max_length=256)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    integration = models.ForeignKey(Integration, null=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.first_name


class Company(models.Model):
    name = models.CharField(max_length=256)
    address = models.CharField(max_length=256)
    city = models.CharField(max_length=256)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.name


class ContactCompany(models.Model):
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE, related_name='job')
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='company')
    job = models.TextField(blank=True, help_text='Job', max_length=5000, null=True)
    started_at = models.DateTimeField(auto_now_add=True)
    finished_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.job

And here is my 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', )

How can I access the company field from the ContactCompany model in this serializer?如何在此序列化程序中从 ContactCompany model 访问公司字段?

Here is how the API response looks like这是 API 响应的样子

{
            "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
            ]
        }

How can I get the job text be desplayed instead of the id?我怎样才能让工作文本而不是 id 被显示?

One possible solution is to used serializerMethodField and get your desire information.一种可能的解决方案是使用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. 


As you did with the others one: its Foreign key on ContactCompany and related_name = 'company'正如您对其他人所做的那样:它在 ContactCompany 和 related_name = 'company' 上的外键

class ContactSerializer(serializers.ModelSerializer): class ContactSerializer(序列化器。ModelSerializer):

company_name = serializers.CharField(source='company.name')
company_ address = serializers.CharField(source='company.name')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取外键模型的字段出现在Django序列化器中? - How to get a field of a foreign key Model appear in a Django-Serializer? 如何从 Serializer 相关字段访问其他 Model 字段? - How to access Other Model Field from Serializer related Field? 如何从外键访问model,Django? - How to access model from Foreign Key, Django? 如何从模型的视图访问序列化器字段? - How to access a Serializer field from the model's View? 如何从链接到另一个模型的外键访问模型字段? - How can I access model fields from a foreign key which is link to another model? 序列化程序中的访问模型字段 - access model field in serializer Django-如何将外键选择限制为另一个模型中的ManyToMany字段 - Django - How to restrict Foreign Key choices to a ManyToMany field in another model 在另一个序列化程序中调用的外键 - foreign key called in another serializer Django / Django Rest Framework-如何允许模型序列化程序将模型的外键字段设置为null? - Django/Django Rest Framework - How do I allow model serializer to set model's foreign key field to null? 如何创建一个模型字段,它是所有另一个外键模型字段的平均值。 例如:平均评分字段 - How to create a model field that is an average of all of another foreign key model' field. Ex: avg rating field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM