简体   繁体   中英

Best way to create Singleton Table in Django/MySQL

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.

PS 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
)
;

This is a bit ugly, and doesn't enforce the constraint at the MySQL level.

If you are worried about enforcement you ought to look at Django's model validation methods. You can write a custom validate_unique that will raise a ValidationError if HitchingPost.objects.count() != 0 .

class HitchingPost(models.Model):
    ...
    def validate_unique(self, exclude = None):
        from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
        if HitchingPost.objects.count() != 0:
            raise ValidationError({NON_FIELD_ERRORS: ["There can be only one!"]})

Is there a better solution?

Hard to say without getting knowing more about your broader requirement.

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.

You can try a custom single element enum . I've never tried anything like it, so take my advice with a pinch of salt.

Is there a mathematical name for such a thing?

Set-once-constant ? I made that up. In truth I have no idea. Better people here will help you out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM