Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query where in

How to do this using django object query:

 SELECT * FROM test WHERE (test_id IN (SELECT test_id FROM test_subject_set)) AND (test_begin_time < '') AND (test_end_time > '') 

The model:

class Test(models.Model):     id = models.AutoField(primary_key=True)     user = models.ForeignKey(User)     groups = models.ManyToManyField(Group)   class TestSubjectSet(models.Model):     id =  models.AutoField(primary_key=True)     test = models.ForeignKey(Test) 
like image 739
kelvinfix Avatar asked May 10 '11 12:05

kelvinfix


People also ask

What is ID __ in in Django?

In Django, we can use the id__in query with a queryset to filter down a queryset based on a list of IDs. However, by default this will fail if your IDs are UUIDs.

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

To filter a Python Django query with a list of values, we can use the filter method with in . to search Blog entries with pk set to 1,4 or 7 by calling Blog. objects. filter with the pk_in argument set to [1, 4, 7] .

What is F in Django Queryset?

In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.


1 Answers

Two querysets is documented way of doing this. It will be one database hit anyway.

test_ids = Subject.objects.all() result = Test.objects.filter(test_id__in=test_ids).filter([some other filtering]) 
like image 171
DrTyrsa Avatar answered Sep 23 '22 21:09

DrTyrsa