Override Django Get or Create

I have a model in which I redefined the save method, so the save method can be passed in some data and automatically fill in the field before saving. Here is my model:

class AccountModel(models.Model):

    account = models.ForeignKey(Account)

    def save(self, request=None, *args, **kwargs):
        if request:
            self.account = request.session['account']
        super(AccountModel, self).save(*args, **kwargs)

    class Meta:
        abstract = True

The idea is that I created a basic model for objects that should be associated with an account, and then I do not have to deal with connections to accounts every time they come (which is a lot). But I would also like to use get_or_create, which saves new objects without passing a request. I know that you can not use get_or_create and use try / except instead, but I would like to know if there is a way to override get_or_create and that this is the right way to do this.

( ), get_or_create QuerySet get_or_create. , , , QuerySet get_or_create? ?

+5
1

django.db.models.query.QuerySet get_or_create, request save, , .

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

Account, QuerySet:

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

:

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

, try-except :)

+4

All Articles