Django rest-framework

亢奇
2023-12-01

Django rest-framework 关联表内容序列化后的显示

数据库表的关系:
category 与 source 是一对多的关系
下面是代码:

models.py

class Category(models.Model):
    name = models.CharField(max_length=30)
    amount = models.IntegerField()
    
class Source(models.Model):
    name = models.CharField(max_length=50)
    rss_link = models.URLField()
    amount = models.IntegerField()
    # 外键
    category = models.ForeignKey(Category)

serializers.py

class SourceSerializers(serializers.ModelSerializer):
    class Meta:
        model = Source
        fields = ("id","name","amount")

class CategorySerializers(serializers.ModelSerializer):
    source = SourceSerializers(many=True,read_only=True)
    
     def get_source(self, obj):
        sources = Source.objects.filter(category=obj)
        return SourceSerializers(sources, many=True, read_only=True).data
        
    class Meta:
        model = Category
        fields = ("id","name","amount","source")

views.py

class CategoryListView(APIView):
    def get(self, request):
        category = Category.objects.all()
        serializers = CategorySerializers(category, many=True)
        return Response(serializers.data)

运行结果:

[
    {
        "id": 1,
        "name": "默认分类",
        "amount": "0",
        "source": [
            {
                "id": 34,
                "name": "博客园",
                "amount": "231"
            },
            {
                "id": 35,
                "name": "CSDN",
                "amount": "643"
            }
        ]
    },
    {
        "id": 2,
        "name": "科技频道",
        "amount": "0",
        "source": []
    }
]

或者
只需要再models.py里面的外键添加一个反向关联的外键名称即可:related_name=“source”
model.py

class Category(models.Model):
    name = models.CharField(max_length=30)
    amount = models.IntegerField()
    
class Source(models.Model):
    name = models.CharField(max_length=50)
    rss_link = models.URLField()
    amount = models.IntegerField()
    # 外键
    category = models.ForeignKey(Category, related_name="source")

开发中遇到的问题:

  • 自定义用户登录的验证函数,当使用python manager.py createsuperuser 创建超级用户的时候,用户登录resetframework 界面出错
    原因:自定义了验证函数,这时就需要根据自定义的函数来创建用户
    总结:
    (1)django系统登录和restframework 的登录都是在一个用户表中存储
    其验证函数当然也是一样的。

参考文章:
https://segmentfault.com/q/1010000008040922

 类似资料: