Django unique_together by subclass model for parent attribute?

In that:

class Administrator(models.Model): user = models.OneToOneField(User, primary_key=True) account = models.ForeignKey(Account) class Meta: unique_together = (('account', 'self.user.username'),) 

The self.user.username part self.user.username clearly incorrect. However, in this:

 class Administrator(User): account = models.ForeignKey(Account) class Meta: unique_together = (('account', 'username'),) 

will work since i inherit from user? (I still cannot verify this because there are too many elements in this place). Can I use the first version with 'user.username' instead? Or should a second version be used?

+7
django django-models
source share
2 answers

This will

 unique_together = (('account', 'user__username'),) 

if I understand what you are trying to do. Note the double underscore. This is how you look at the properties of a foreign key object.

+7
source share

I do not believe that you can do what you are trying to do using the django core. As indicated in this answer to a related question, unique_together is applied at the database level. If you check the DB tables created by inheriting the django model, you will see that it is not possible to execute the database.

Take a look at this related question for some alternative solutions.

+5
source share

All Articles