Skip to main content
 首页 » 编程设计

python之在 DRF 中显示 ForeignKey 属性

2025年01月19日14lvdongjie

当我运行 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() 

请您参考如下方法:

一种解决方案是将 GetProductSerializer 的 category 和 subcategory 字段定义为 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