Home > Blockchain >  Find queryset where one field is greater than another one
Find queryset where one field is greater than another one

Time:11-02

I have model Shop, I want to get all shops which time_open(opening time) is more than time_closed(closing time). For example 23:00:00 is more than 07:00:00 (Shop_2(Night shift shop)).

class Shop(models.Model):
    time_open = models.TimeField()
    time_closed = models.TimeField()

for example i have two objects:

shop_1 = {
    "time_open": "08:00:00",
    "time_closed": "22:00:00"
}

shop_2 = {
    "time_open": "23:00:00",
    "time_closed": "07:00:00"
}

My goal is to output queryset in which shop_2 would be. These timestamps in these objects only for visual example, i want to do it without putting any data in sql query. I want to achive this by comparing time_open and time_closed fields.

I found similar question in pure SQL:

Find rows where one field is greater than another one

My goal is to do it with Django ORM.

CodePudding user response:

You can take a look at django's F objects, it allows you to filter objects based on their field values.

from django.db.models import F
Shop.objects.filter(time_open__gt=F('time_closed'))
  • Related