首页 > 解决方案 > 使用外键名称过滤 Django ViewSet

问题描述

我有 2 个具有以下结构的 Django 模型:

class Title(models.Model):
    id = models.AutoField(primary_key=True)
    code = models.CharField(unique=True, max_length=256)

class Component(models.Model):
    id = models.AutoField(primary_key=True)
    code = models.CharField(unique=True, max_length=256)
    title = models.ForeignKey('Title', on_delete=models.PROTECT)

所以我有一个 ComponentViewSet 如下:

class ComponentViewSet(viewsets.ModelViewSet):

    queryset = Component.objects.all()
    serializer_class = ComponentSerializer

    filter_fields = {
        'id': ['exact'],
        'code': ['exact', 'istartswith'],
        'title': ['exact'],
    }

因此,如果我想通过 Title 过滤组件,则 URL 为http://localhost:8010/api/components/?title=1。如何使用 Title.code 值进行视图过滤,即http://localhost:8010/api/components/?title=Test

标签: djangodjango-rest-frameworkdjango-views

解决方案


尝试这个

class ComponentViewSet(viewsets.ModelViewSet):

    queryset = Component.objects.all()
    serializer_class = ComponentSerializer

    filter_fields = {
        'id': ['exact'],
        'code': ['exact', 'istartswith'],
        'title__code': ['exact'],
    }

但是,网址会变成,

 http://localhost:8010/api/components/?title__code=Test


建议
您可以使用django-filter,它可以更好地控制URL 过滤


推荐阅读