Reputation: 63
I have a model which stores login logout time and date for users
class LoginLogout(models.Model):
username = models.CharField(max_length=30, unique=True)
date = models.DateField(auto_now_add=True)
login_time = models.TimeField()
logout_time = models.TimeField(null=True, blank=True)
Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset.
Upvotes: 1
Views: 884
Reputation: 32347
I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input.
You want to learn about Django's query expressions.
events = LoginLogout.objects.filter(
username=username,
date__ge=date_from,
date__le=date_to,
)
Any field can be blank. If username is blank all results will be returned.
Those are special conditions, and should be represented as such in your code.
filter_args = {}
if username:
filter_args['username'] = username
if date_from:
filter_args['date__ge'] = date_from
if date_to:
filter_args['date__le'] = date_to
events = LoginLogout.objects.filter(**filter_args)
Upvotes: 2
Reputation: 3371
try this:
from django.db.models import Q
if username or date_from or date_to:
LoginLogout.objects.filter(
Q(username=username),
Q(date__gt='date_from'),
Q(date__lt='date_to')
)
else:
LoginLogout.objects.all()
Upvotes: 0
Reputation: 597
you have to use many if else...
i just give you the query
# Case 1: All res:
res = LoginLogout.objects.all()
# Case 2: date_to is blank:
res = LoginLogout.objects.filter(login_time__gt = date_from)
# Case 3: date_from is blank
res = LoginLogout.Objects.filter(logout_time__lt = date_to)
# Case 4: all value
res = LoginLogout.Objects.filter( Q(username= username) & Q(login_...) & Q(logout_...)
# Or:
res = LoginLogout.Objects.filter(username= username, login_time__gt = ...)
Upvotes: 0
Reputation: 1623
This should do the work :
if not username:
return LoginLogout.objects.all()
else:
return LoginLogout.objects.filter(date__gte=date_from,
date__lte=date_to,
username=username)
Upvotes: 2