Jeremiasz1
Jeremiasz1

Reputation: 63

Django 'dynamic' filtering

I have a list , l = ['XXX', 'YYY']

And I need filtred my model with this elements of list (number of this elements wouldn't be constant)

For example. I have code field in my model, and there is few elements with code "XXX", few with code "YYY", few with "ZZZ", etc. And I have a list which contains -for example- ['XXX', 'YYY'] And I need to get records with code XXX and YYY from db.

I have no idea when I can start.

Upvotes: 2

Views: 239

Answers (2)

iankit
iankit

Reputation: 9352

Letsay you have a model in Django for storing cars your garage has.

class Car(models.Model):
    manufactirer = models.Charfield(max_length=100)
    make = models.DatetimeField()
    anotherfield = ...... 

Now to filter these cars by name of manufacturer, you can do :

Car.objects.filter(manufacturer='BMW')

In case you you want to filter cars by all german makers you can do something like this :

manufacturer_list = ['BMW', 'VW', 'AUDI']
Car.objects.filter(manufacturer__in=manufacturer_list)

This is the SQL equivalent of

SELECT ... WHERE manufacturer IN ('BMW', 'VW', 'AUDI');

You can also use a queryset to dynamically fetch the list of values first. This is valuable in the case of when manufacturers list comes from a django query.

manufacturer_list = Manufacturer.objects.filter(name__contains='mer')
cars = Car.objects.filter(manufacturer__in=manufacturer_list)

Upvotes: 4

Anush Devendra
Anush Devendra

Reputation: 5475

Your list:

lst = ['XXX', 'YYY']

Now you can filter like:

elements = Model.objects.filter(code__in=lst)

Upvotes: 4

Related Questions