Filtering in django rest framework

2024/10/11 22:27:20

In my project I use django rest framework. To filter the results I use django_filters backend. There is my code:

models.py

from django.db import modelsclass Region(models.Model):name = models.CharField(max_length=100, blank=True, null=False)class Town(models.Model):region = models.ForeignKey(Region)name = models.CharField(max_length=100, blank=True, null=False')

filters.py

import django_filters
from models import Townclass TownFilter(django_filters.FilterSet):region = django_filters.CharFilter(name="region__name", lookup_type="contains")town = django_filters.CharFilter(name="name", lookup_type="contains")class Meta:model = Townfields = ['region', 'town']

views.py

from models import Town
from rest_framework import generics
from serializers import TownSerializer
from filters import TownFilterclass TownList(generics.ListAPIView):queryset = Town.objects.all()serializer_class = TownSerializerfilter_class = TownFilter

So, I can write ?region=Region_name&town=Town_name to the end of the request url, and the result will be filtered.

But I want to use only one get param in the request url, which can have region or town name as value. For example ?search=Region_name and ?search=Town_name. How can I do this?

Answer

There are a few options, but the easiest way is to just override 'get_queryset' in your API view.

Example from the docs adapted to your use case:

class TownList(generics.ListAPIView):queryset = Town.objects.all()serializer_class = TownSerializerfilter_class = TownFilter(generics.ListAPIView)serializer_class = PurchaseSerializerdef get_queryset(self):queryset = Town.objects.all()search_param = self.request.QUERY_PARAMS.get('search', None)if search_param is not None:"""set queryset here or use your TownFilter """return queryset

Another way is to set your search_fields on the list api view class in combination use the SearchFilter class. The problem is that if you're filtering over multiple models, you may have to do some additional implementation here to make sure it's looking at exactly what you want. If you're not doing anything fancy, just put double underscores for region for example: region__name

https://en.xdnf.cn/q/69727.html

Related Q&A

Efficiency difference between dict.has_key and key in dict in Python [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicate:has_key() or in? In Python, therere two ways of deciding whether a key is in a dict:if dict.has_key(key) and if key in di…

python points to global installation even after virtualenv activation

Its a bit weird, I have activated the virtual environment python still points to the global installation.$ which python /usr/bin/python$ source ~/virtualenv/bin/activate (virtualenv)$ which python /usr…

Should I perform both lemmatization and stemming?

Im writing a text classification system in Python. This is what Im doing to canonicalize each token:lem, stem = WordNetLemmatizer(), PorterStemmer() for doc in corpus:for word in doc:lemma = stem.stem(…

Python monkey patch private function

I have a module with a function (call it a()) that calls another function defined in the same module (call it __b()). __b() is a function which speaks to a website via urllib2 and gets some data back.…

How to interleave numpy.ndarrays?

I am currently looking for method in which i can interleave 2 numpy.ndarray. such that>>> a = np.random.rand(5,5) >>> print a [[ 0.83367208 0.29507876 0.41849799 0.58342521 0.818…

Object is not subscripable networkx

import itertools import copy import networkx as nx import pandas as pd import matplotlib.pyplot as plt #-- edgelist = pd.read_csv(https://gist.githubusercontent.com/brooksandrew /e570c38bcc72a8d1024…

WTForms : How to add autofocus attribute to a StringField

I am rather new to WTForms, Flask-WTF. I cant figure out how to simply add the HTML5 attribute "autofocus" to one of the form field, from the form definition. I would like to do that in the P…

Image rotation in Pillow

I have an image and I want to transpose it by 30 degrees. Is it possible to do by using something like the following?spinPicture003 = Picture003.transpose(Image.Rotate_30)

Python code to calculate angle between three points (lat long coordinates)

Can anybody suggest how to calculate angle between three points (lat long coordinates)A : (12.92473, 77.6183) B : (12.92512, 77.61923) C : (12.92541, 77.61985)

z3: solve the Eight Queens puzzle

Im using Z3 to solve the Eight Queens puzzle. I know that each queen can be represented by a single integer in this problem. But, when I represent a queen by two integers as following:from z3 import *X…