0

I have created a (kind of) singleton to put all the app parameters in my database:

class SingletonModel(models.Model):

    def save(self, *args, **kwargs):
        self.pk = 1
        super(SingletonModel, self).save(*args, **kwargs)

    @classmethod
    def load(cls):
        return cls.objects.all().get()

    class Meta:
        abstract = True


class AppParameters(SingletonModel, models.Model):

    DEFAULT_BALANCE_ALERT_THRESHOLD = models.PositiveIntegerField(default=5)
    # other parameters...

It worked pretty well, until I tried to use one of these parameters in a default attribute of a model field:

class Convive(models.Model):

    balance_alert_threshold = models.IntegerField(
        default=AppParameters.load().DEFAULT_BALANCE_ALERT_THRESHOLD,
        blank=True,
        null=True)

This seemed to work too, but when I use a script to reinitialise local data, the first manage.py migrate produce a DoesNotExist since my Singleton does not exist yet. It happens because of a file importing Convive model.

How would you solve this? Is there a way to "delay" the evaluation of the default field?

Thanks.

EDIT After posting this, I think that if my code processes db queries at import time, something may be wrong with it...

1 Answer 1

1

Create a method that returns the default value,

def get_default_balance_alert_threshold():
    return AppParameters.load().DEFAULT_BALANCE_ALERT_THRESHOLD

then use that method as your default.

class Convive(models.Model):
    balance_alert_threshold = models.IntegerField(
        default=get_default_balance_alert_threshold,
        blank=True,
        null=True,
    )
Sign up to request clarification or add additional context in comments.

1 Comment

Simple and clever, thanks! That solved both problem (DoesNotExist error and potential DB queries run at import time)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.