V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
lsymy
V2EX  ›  Python

DRF ModelViewSet django-filter 如何筛选关联表字段?

  •  
  •   lsymy · 2022-08-08 19:13:25 +08:00 · 1486 次点击
    这是一个创建于 620 天前的主题,其中的信息可能已经有所发展或是发生改变。

    python 新手,一个简单的筛选把我搞懵逼了。 第一个 model: electrode

    from django.db import models
    
    # Create your models here.
    
    class Electrode(models.Model):
        name = models.CharField(max_length=32, null=True)
    

    第二个 model: electrode_log

    from django.db import models
    from Application.views.electrode.models import Electrode
    
    # Create your models here.
    
    class ElectrodeLog(models.Model):
        electrode = models.ForeignKey(Electrode, on_delete=models.CASCADE, default=None, null=True)
    

    用的视图集 ModelViewSet ,求教怎么在筛选到 Electrode 表的 name ,万分感激。

    1 条回复    2022-08-08 20:48:08 +08:00
    gotounix
        1
    gotounix  
       2022-08-08 20:48:08 +08:00
    from django_filters import rest_framework as filters
    from rest_framework import viewsets

    class ElectrodeLogFilter(filters.FilterSet):
    ....electrode__name = filters.CharFilter(lookup_expr='icontains')

    class ElectrodeLogViewSet(viewsets.ModelViewSet):
    ....filterset_class = ElectrodeLogFilter

    ....为空格
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1894 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 16:17 · PVG 00:17 · LAX 09:17 · JFK 12:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.