在DRF中显示ForeignKey属性

时间:2017-10-31 17:52:33

标签: python django django-rest-framework

当我运行api时,我没有获得category名称和subcategory名称,而是获得了他们的身份,

[
    {
        "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()

1 个答案:

答案 0 :(得分:1)

一种解决方案是将category的{​​{1}}和subcategory字段定义为GetProductSerializer

  

StringRelatedField可用于使用 unicode 方法表示关系的目标。

http://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield

或者,类似地,StringRelatedFields

  

SlugRelatedField可用于使用目标上的字段来表示关系的目标。

http://www.django-rest-framework.org/api-guide/relations/#slugrelatedfield