python - 在 DRF 中显示 ForeignKey 属性

标签 python django django-rest-framework

当我运行 api 时,我得到的不是 category 名称和 subcategory 名称,而是它们的 id,

[
    {
        "id": 1,
        "name": "StrawBerry",
        "category": 1,
        "subcategory": 1
    }
]

我其实想要这样的东西:

[
    {
        "id": 1,
        "name": "StrawBerry",
        "category": "Fruits",
        "subcategory": "Berries"
    }
]

注意:我已经有了类别和子类别。我只想知道如何访问它们。

模型.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

序列化器.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()

最佳答案

一种解决方案是将 GetProductSerializercategorysubcategory 字段定义为 StringRelatedFields:

StringRelatedField may be used to represent the target of the relationship using its unicode method.

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

或者,类似地,作为 SlugRelatedFields:

SlugRelatedField may be used to represent the target of the relationship using a field on the target.

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

关于python - 在 DRF 中显示 ForeignKey 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47041697/

相关文章:

python - 如何从 findHomography 获取旋转角度?

python - Django View 查询和外键查找

javascript - 将 angular $http 与 django urlpatterns 一起使用以获取 json 文件

django - 如何在 django 命令中使用多进程?

python - Django swagger-如何从删除、放置方法中禁用 DjangoFilterBackend 查询过滤器?

Django rest 框架 - 序列化程序中的字段级验证

python - 如何比较 python 中的变量类型?

python - Django - 将属性值传递给 TemplateView 中的 as_view

rest - 是不是rest API路由按权限分开比较好?

python - 在 Python for 循环中创建一个计数器