Django queryset checking existence having unexpected behavior

I have a model like this

class Student(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    archived = models.BooleanField(default=False)

    class Meta:
        constraints = [
            UniqueConstraint(
                fields=["first_name", "last_name"], condition=Q(archived=False), name="unique_user"
            )
        ]

and code like below

d = {"first_name": "John", "last_name": "Doe"}
students = Student.objects.filter(first_name=d.get("first_name"), last_name=d.get("last_name"))

for student in students:
   """Doing some stuff here"""
   pass

if not students:
  Student.objects.create(first_name=d.get("first_name"), last_name=d.get("last_name"))

I am getting an integrity error from the last line where I call objects.create

duplicate key value violates unique constraint "unique_user" DETAIL: Key (first_name, last_name)

In the objects.filter() I have two fields that are part of the unique constraint, and I am using the same queryset before the objects.create is called, so this error should not happen unless something going wrong with the queryset. This code is working without issues most of the time. Only once this error was raised. Any idea what is going on ? One possibility is that between the filter query and the create query the object was created and the integrity error was raised from create query. But that was not the case. I checked the db, there was nothing created. Infact there was already data which was created hours before matching these conditions. So the filter query returned a non empty queryset and the create query should not even been called.

Back to Top