[英]Displaying ForeignKey attributes in DRF
When I run the api, instead of getting category
name and subcategory
name, I get their id,当我运行 api 时,我得到的不是category
名称和subcategory
名称,而是它们的 ID,
[
{
"id": 1,
"name": "StrawBerry",
"category": 1,
"subcategory": 1
}
]
I actually want something like this:我实际上想要这样的东西:
[
{
"id": 1,
"name": "StrawBerry",
"category": "Fruits",
"subcategory": "Berries"
}
]
Note: I already have category and subcategory.注意:我已经有了类别和子类别。 I just want to know how to access them.我只想知道如何访问它们。
models.py模型.py
from django.db import models
class Category(models.Model):
category = models.CharField(max_length=200)
parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
class Meta:
unique_together = ('parent' , 'category')
def __str__(self):
return self.category
class SubCategory(models.Model):
subcategory = models.CharField(max_length=200)
category = models.ForeignKey('Category', null=True, blank=True)
parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren')
class Meta:
unique_together = ('parent' , 'subcategory')
def __str__(self):
return self.subcategory
class Product(models.Model):
name = models.CharField(max_length=200)
category = models.ForeignKey('Category', null=True, blank=True)
subcategory = models.ForeignKey('SubCategory', null=True, blank=True)
def __str__(self):
return self.name
serializers.py序列化程序.py
class GetProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name', 'category', 'subcategory')
views.py视图.py
class GetProductViewSet(viewsets.ModelViewSet):
serializer_class = GetProductSerializer
queryset = Product.objects.all()
One solution would be to define the category
and subcategory
fields of your GetProductSerializer
as StringRelatedFields
:一种解决方案是将GetProductSerializer
的category
和subcategory
字段定义为StringRelatedFields
:
StringRelatedField may be used to represent the target of the relationship using its unicode method. StringRelatedField 可用于使用其unicode方法表示关系的目标。
http://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield http://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield
Or, similarly, as SlugRelatedFields
:或者,类似地,作为SlugRelatedFields
:
SlugRelatedField may be used to represent the target of the relationship using a field on the target. SlugRelatedField 可用于使用目标上的字段来表示关系的目标。
http://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield http://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.