Event has two DateTimeField's and i need to compare them to the actual date time in a same method.
from django.utils import timezone
event_starts = models.DateTimeField(_("Event starts"))
registration_closes_at = models.DateTimeField(
_("Registration ends:"), null=True, blank=True
)
This is what i have tried, but it doesn't work. So what i need is: If event has been started or registration was closed user can not attend this event.
def is_registration_open(self):
now = timezone.now()
passed_registration = now > self.registration_closes_at
passed_start = now > self.event_starts
if not passed_registration or not passed_start:
return
And tried this:
def is_registration_open(self):
if (
not timezone.now() > self.registration_closes_at
or not timezone.now() > self.event_starts
):
return
Here is a fail:
'>' not supported between instances of 'datetime.datetime' and 'NoneType'
When i compare only event_starts everything is working fine.
Thanks for help!
Notice that registration_closes_at
field is nullable, therefore you need to handle that case in the condition.
My guess is that you would like to ignore the registration_closes_at
when it is null, so the condition would look like:
def is_registration_open(self):
if self.registration_closes_at:
# before registration closes
return timezone.now() < self.registration_closes_at
else:
# before event starts
return timezone.now() < self.event_starts
Even better option is to use annotation and check the condition on the database for better performance
from django.db.models import Count, Case, When, Value, BooleanField
from django.db.models.functions import Now
MyModel.objects.annotate(
can_register=Case(
When(registration_closes_at__gt=Now(), then=Value(True)),
When(event_starts__gt=Now(), then=Value(True)),
default=Value(False),
output_field=BooleanField(),
)
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.