views:

65

answers:

1

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
)
;
+2  A: 

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.

Manoj Govindan