我有两个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'],
}
因此,如果我想通过标题过滤组件,URL是http://localhost:8010/api/components/?title=1.如何使用Title.code值进行视图筛选,即http://localhost:8010/api/components/?title=Test?
尝试这个
class ComponentViewSet(viewsets.ModelViewSet):
queryset = Component.objects.all()
serializer_class = ComponentSerializer
filter_fields = {
'id': ['exact'],
'code': ['exact', 'istartswith'],
'title__code': ['exact'],
}
但是,url将变为
http://localhost:8010/api/components/?title__code=Test
建议
您可以使用django过滤器,它对URL过滤有更多控制