2017-10-30 7 views
0

이 질문은 this one으로 확대됩니다.django-filter 및 DRF : lookupfield의 AND 절

내 모델

class Car(models.Model): 
    images = models.ManyToManyField(Image) 

class Image(models.Model): 
    path = models.CharField() 
    type = models.CharField() 

을하고 내 필터 클래스가
class CarFilter(django_filters.FilterSet): 
    having_image = django_filters.Filter(name="images", lookup_type='in') 

    class Meta: 
     model = Car 

다음 내가 ?having_image=5 같은 쿼리를 GET하고 pk=5와 이미지가 모든 차를 얻을 수있다 가정하자. 괜찮아. 그러나 만일 내가이 이미지와 함께 양쪽 차를 돌려 줄 필요가 있으면 그리고 어떤 이미지도없는 차를 1 개의 목록에 넣어야 할까? 하나의 조건을 두 가지로 통합하려면 어떻게합니까? django_filters.Filter?

+0

이 답변은 https://stackoverflow.com/questions/41194200/django-filter-with-drf-how-to-do-and-when-applying-multiple- values-with- 답에서 찾을 수 있습니다. . 당신이 아직도 의심을 가지고 있다면 한번보세요. –

답변

0

django-filter가 지원되지 않는다고 생각하지 않습니다. 자신의 Filter 클래스를 만들고 filter() 메서드를 재정의 할 수 있습니다.

Querysets는 | (조합) 연산자를 지원하므로 기본 결과와 필드 결과가 None 인 결과를 결합 할 수 있습니다.

class AndNoneFilter(django_filters.Filter): 

    def filter(self, qs, value): 
     return qs(**{self.field_name: None}) | super().filter(qs, value) 

class CarFilter(django_filters.FilterSet): 
    having_image = AndNoneFilter(field_name='images', lookup_type='in') 

이 코드는 테스트하지 않았으므로 작성한대로 작동하지 않을 수도 있지만 아이디어를 얻을 수 있습니다.