I want a table which can only have one record. My current solution is:
class HitchingPost(models.Model):
SINGLETON_CHOICES = (('S', 'Singleton'),)
singleton = models.CharField(max_length=1, choices=SINGLETON_CHOICES, unique=True, null=False, default='S');
value = models.IntegerField()
def __unicode__(self):
return u"HitchingPost" # only ever one record
This is a bit ugly, and doesn’t enforce the constraint at the MySQL level.
Is there a better solution?
Is there a MySQL field type which can only have one value (boolean is the smallest I’ve found, having two possibilities)? A base-0 digit is the nearest I’ve come to expressing the concept.
Is there a mathematical name for such a thing?
Thanks,
Chris.
P.S. Generated SQL is:
CREATE TABLE `appname_hitchingpost` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`singleton` varchar(1) NOT NULL UNIQUE,
`value` integer NOT NULL
)
;
If you are worried about enforcement you ought to look at Django’s model validation methods. You can write a custom
validate_uniquethat will raise aValidationErrorifHitchingPost.objects.count() != 0.Hard to say without getting knowing more about your broader requirement.
You can try a custom single element
enum. I’ve never tried anything like it, so take my advice with a pinch of salt.Set-once-constant? I made that up. In truth I have no idea. Better people here will help you out.