Thursday, July 8, 2021

DJango queries with Q

Example 


class MyModel(models.Model):

    name = models.CharField(max_length=10)

    model_num = models.IntegerField()

    flag = models.NullBooleanField(defaul



We can use Q objects to create AND , OR conditions in your lookup query. For example, say we want all objects that have flag=True OR model_num>15.



from django.db.models import Q

MyModel.objects.filter(Q(flag=True) | Q(model_num__gt=15))


The above translates to WHERE flag=True OR model_num > 15 similarly for an AND you would do.


MyModel.objects.filter(Q(flag=True) & Q(model_num__gt=15))



Note: Q objects can be used with any lookup function that takes keyword arguments such as filter, exclude, get. Make sure that when you use with get that you will only return one object or the MultipleObjectsReturned exception will be raised.



References:

https://riptutorial.com/django/example/4565/advanced-queries-with-q-objects


No comments:

Post a Comment