[英]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.