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
How to Improve the Label Placement in Scatter Plot
How to Write Binary Data to Stdout in Python 3
Django Return Redirect() with Parameters
Fastest Way to Take a Screenshot with Python on Windows
Python Datetime Object Show Wrong Timezone Offset
Product Code Looks Like Abcd2343, How to Split by Letters and Numbers
Remove Namespace and Prefix from Xml in Python Using Lxml
Getting One Value from a Tuple
How to Run Pygame or Pyglet in a Browser
What Does "Bound Method" Error Mean When I Call a Function
How to Extract an Arbitrary Line of Values from a Numpy Array
How to Terminate a Thread When Main Program Ends
Pip - Fatal Error in Launcher: Unable to Create Process Using '"'
How to Solve Readtimeouterror: Httpsconnectionpool(Host='Pypi.Python.Org', Port=443) with Pip
What Is the Advantage of a List Comprehension Over a for Loop