How to Filter a Django Query with a List of Values

How can I filter a Django query with a list of values?

From the Django documentation:

Blog.objects.filter(pk__in=[1, 4, 7])

How to filter in a table column contains list in django

object = Models.objects.filter(A__contains=id)

Django - How to query a list inside of a filter method

We can use a subquery to obtain the last user, and then filter accordingly:

from django.db.models import OuterRef, Subquery, Q

Batch.objects.annotate(
last_user=Subquery(
BatchLogComment.objects.filter(
batch=OuterRef('pk')
).order_by('-created_at').values('user')[:1]
)
).filter(
~Q(last_user=self.request.user),
comments__user=self.request.user
)

get first object from every type in Django query

Yes, there is a manual way.

type_list = [1,2,3,4]
new_list = []

for each_type in type_list:
latest_obj = MyModel.objects.filter(type=each_type).order_by('-created_at').first()
new_list.append(latest_obj)

This new_list contains the latest object or each type.

Or

objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('type', '-created_at').distinct('type')

Reference: Django distinct

Check if each value within list is present in the given Django Model Table in a SINGLE query

If you know you're passing in N pks, then a count() query filtered by those pks should have exactly N results.

def do_exist(model, pks):
return model.objects.filter(pk__in=pks).count() == len(pks)

Django - Filter out All Values from one Field in Model and Delete

You could use the update() function however this would not save the values.

Therefore, I would suggest iterating the filtered queryset and change the field to None assuming null=True in your model definition.

qs_to_remove = Data_Repo1.filter(user=request.user)
for instance in qs_to_remove:
instance.date1 = None
instance.save()

Django JSONField query on a list of values where at least 1 value is in the filter list

use contained_by instead of contains

Movie.objects.all().distinct().filter(genres__contained_by = wanted_genres)

For more information you can check official documentation



Related Topics



Leave a reply



Submit