I am using a django model to store start date and end date for the date rate I want to be active for the whole project. There can exist activities in my project outside the date range and these are the ones I want filtered out in all my views.
Is there a way to use this model (I call it GlobalDateSettings) as a sort of a constant, singleton or the like, so I can only ever change it and not make new instances, since I only ever want one start date, and one end date?
Right now I am using kind of a workaround via the Model.objects.first() but I am thinking there must be a more Django-standard or pythonic way?
Donāt know if it helps, but my models is:
class GlobalDateSettings(models.Model):
start_date = models.DateField()
end_date = models.DateField()
def save(self, *args, **kwargs):
if not self.pk and GlobalDateSettings.objects.exists():
raise ValidationError("There can only be one instance of GlobalDateSettings")
return super(GlobalDateSettings, self).save(*args, **kwargs)
Can you physically prevent the addition of new rows?
Only if you implement a trigger in the database to prevent new rows from being added.
However, if you limit your concerns to what is done in Django, itās a lot easier.
If you donāt write any code that inserts into that model, then youāre never going to add rows. If you need to prevent the admin from adding rows, you can do that, too.
Django doesnāt just go around adding rows to models - if a row is being added, itās because there is code to do that. So donāt do that.
Yes. I can see now, that I can limit it to an UpdateView only accessible to the admin user. Thank you.
Is creating a model to only ever store one instance of āproject settingsā like this āModel.objects.first()ā the preferred way or am I missing something?
We do a couple different things simiar to this depending upon need.
Itās rare for us to only have one value that needs to be set as a project-level setting. So one of the things we do is create a Settings model.
This model has a field for the setting name, and fields for a charfield, boolean, integer and Decimal. The setting name is the primary key, ensuring that thereās only one instance in the model with that name, and only one of the data fields gets populated.
No. Thereās one row for each setting. That setting is identified by the field name. Only one of the _val fields get populated for each row, the other fields remain null.
To use your example, weād need to extend our Settings model to add a date field. (We donāt have any settings needing a date, so we donāt have it in our model.) date_val = models.DateField(...)
To create your example, it would be something like:
Settings.objects.create(name=āstart_dateā, date_val=ā2024-03-01ā)
Settings.objects.create(name=āend_dateā, date_val=ā2024-03-31ā)