Skip to content

Instantly share code, notes, and snippets.

@pulkitpahwa
Last active October 4, 2020 06:44
Show Gist options
  • Save pulkitpahwa/a6ec21da55aeffb3b14ce23dc865cbbe to your computer and use it in GitHub Desktop.
Save pulkitpahwa/a6ec21da55aeffb3b14ce23dc865cbbe to your computer and use it in GitHub Desktop.
An example on how to use F expressions
import uuid
from django.db import models
# assuming we have our User model implemented in the users app
from users.models import User
class Contest(models.Model):
# I prefer using UUID field instead of auto increment for storing id
id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
contest_name = models.CharField(max_length=100)
start_time = models.DateTimeField(auto_now_add=True)
end_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.contest_name
class ContestParticipant(models.Model):
id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
contest = models.ForeignKey(Contest, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
registration_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.get_full_name()
# Querying ContestParticipant where registration_time > contest__end_time
from django.db.models import F
late_registrations = ContestParticipant.objects.filter(
registration_time__gt=F('contest__end_time')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment