当我运行api时,没有获取category
名称和subcategory
名称,而是获取了它们的ID,
[
{
"id": 1,
"name": "StrawBerry",
"category": 1,
"subcategory": 1
}
]
我实际上想要这样的东西:
[
{
"id": 1,
"name": "StrawBerry",
"category": "Fruits",
"subcategory": "Berries"
}
]
注意:我已经有类别和子类别。我只想知道如何访问它们。
models.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
class GetProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name', 'category', 'subcategory')
views.py
class GetProductViewSet(viewsets.ModelViewSet):
serializer_class = GetProductSerializer
queryset = Product.objects.all()
最佳答案
一种解决方案是将category
的subcategory
和GetProductSerializer
字段定义为StringRelatedFields
:
StringRelatedField可以使用其unicode方法来表示关系的目标。
http://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield
或者类似地,作为SlugRelatedFields
:
SlugRelatedField可用于使用目标上的字段表示关系的目标。
http://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield