简体   繁体   中英

django-filter filtering across multiple models with foreign keys

The problem

I'm using the django-filter package to filter through my results. Suppose my models look like the following:

class Material(models.Model):
    name = models.CharField(...)

class Test1(models.Model):
    id
    materialTested = models.ForeignKey(...)
    TestResult = models.DecimalField(...)
class Test2(models.Model):
    id
    materialTested = models.ForeignKey(...)
    TestResult = models.DecimalField(...)

I am trying to filter using the package using results from both Test1 and Test2. The reason the tests are their own models is because multiples of the same test (or none) can be run for the same materials

Current Progress I currently have it set up to filter using a single test by defining the following filter:

class Filter1(django_filters.FilterSet):
   class Meta:
      model = Test1
      fields = {'TestResult':['gte','lte']}

The goal

The goal is to be able to filter with results from both tests (Returning the materials to the list). For example, the fields part of the Meta would look like:

fields={'TestResult':['gte','lte'], 'TestResult__fromTest2':['gte','lte']}

I know that wouldn't work because Test2 isn't mentioned anywhere and I'm pretty sure the second part of the filter isn't written correctly. Any help is appreciated!

I found the answer later in the day, if any one is interested.

The correct syntax would be to create the filter using the Material model such as:

class MaterialFilter(django_filters.FilterSet):
    ....

and in the filter Meta use:

fields={'test1__TestResult':['methods','here'], 'test2__TestResult':['methods','here']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM