Dry Unique Objects in Django

I want the object to be unique, and to cause an error when the user tries to save it (for example, through the administrator), if not? The only thing I mean is that some attributes of objects can contain the same values ​​as other objects, but they cannot be identical to other values ​​of the object.

If I'm not mistaken, I can do it like this:

class Animal(models.Model):
    common_name = models.CharField(max_length=150)
    latin_name = models.CharField(max_length=150)
    class Meta:
        unique_together = ("common_name", "latin_name")

But then every time I reorganize the model (for example, to add a new field or change the name of an existing field), I also need to edit the list of fields in brackets assigned to unique_together . With a simple model, this is normal, but with significant, it becomes a real problem during refactoring.

How can I avoid repeating the input of the list of field names in the unique_together bracket ? Is there a way to pass the list of model fields to a variable and assign this variable instead of unique_together ?

+5
source share
1 answer

Model refactoring is a rather expensive thing:

  • You will need to change all the code using your models, as the field names correspond to the properties of the object
  • You will have to change your database manually, because Django cannot do this for you (at least the version that I used the last time I worked with Django could not)

, - , .

EDIT. , " ", freenode , . , , Django.

Django ORM "magic" ModelBase (django.db.models.base.ModelBase) Model. , .

, :

  • ModelBase .
  • __new__(cls, name, bases, dict)
  • dict, Meta (dict["Meta"]),
  • meta.unique_together , .
  • (ModelBase.__new__)
  • __metaclass__ = MyMetaclass ( , Model )
+4

All Articles