[Fixed]-Override Django get_or_create

21👍

You could subclass django.db.models.query.QuerySet and override the get_or_create method there to accept your request keyword argument and pass it onto save I guess, but it isn’t very pretty.

class AccountQuerySet(models.query.QuerySet):
    def get_or_create(...):
        ...

You could then add a custom manager to your Account model which uses this custom QuerySet:

class AccountManager(models.Manager):
    def get_queryset(self):
        return AccountQuerySet(self.model)

Then use this manager in your model:

class Account(models.Model):
    ...
    objects = AccountManager()

But you might find that the try-except method is neater after all 🙂

Leave a comment