BOMBOLOM.COM

(django) Compose Field and set Unique

Posted by José Lopes.

This post shows how to create a model in Django with an attributes composed by other two, assuring its unicity.

Lets imagine that we have the following model:

class ExampleModel( models.Model ):
    first_part = models.ForeignKey(OtherModel)
    second_part = models.CharField(max_length=8)
    fullname = models.CharField(max_length=19, blank=True, editable=False)

    def save(self):
    	self.fullname = '%s-%s' % (self.first_part, self.second_part)
        super(ExampleModel,self).save()

In this model we have the attribute fullname, that is not editable from the admin page and its generated overriding the save method, following a pre-determinated formula with the first_part and second_part attributes as base.

This example can easily be found on the web. I intentionally used two attributes where one of them is a ForeignKey just to show that any kind of field may be used, though its clear that using a ManyToMany field doesn't make much sense.

Now I still want that the fullname attribute to be unique, and this is the subject that I wanted to aboard in this post.

We may have the temptation to include the unicity directly on the attribute.

fullname = models.CharField(max_length=19, blank=True, editable=False, unique=True)

This places the problem for the multiple accesses to the application. Since we have for the attribute the None value as default, it will cause us problems in this kind of access resulting in error messages stating that the value already exists. This in my opinion is not aceptable.

The solution is very simple and appeals to the Meta class. Our model becomes:

class ExampleModel( models.Model ):
    first_part = models.ForeignKey(OtherModel)
    second_part = models.CharField(max_length=8)
    fullname = models.CharField(max_length=19, blank=True, editable=False)

    class Meta:
        unique_together = (('first_part', 'second_part'))

    def save(self):
    	self.fullname = '%s-%s' % (self.first_part, self.second_part)
        super(ExampleModel,self).save()

The code in red does the magic to assure the unicity of the first_part and second_part attributes, and since both make the fullname we also assure the unicity of this last one.

2008.05.23 | There's more... | Comments 0 | Tags ,

Deixe a sua mensagem:

Nome:


E-mail:


URL:


Comment:

Secret number

To send you comment you must insert the "secret number" on the box


Made with PyBlosxom | Add to Google