推荐学习书目
› 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 · Aug 8, 2022 · 2499 views
    This topic created in 1508 days ago, the information mentioned may be changed or developed.

    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 replies  •  2022-08-08 20:48:08 +08:00
    gotounix
        1
    gotounix  
       Aug 8, 2022
    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

    ....为空格
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2373 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 10:37 · PVG 18:37 · LAX 03:37 · JFK 06:37
    ♥ Do have faith in what you're doing.