Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django unique_together on sub-class model for parent attribute?

In this:

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 is obviously incorrrect. However, in this:

class Administrator(User):
    account = models.ForeignKey(Account)

    class Meta:
        unique_together = (('account', 'username'),)

would that work since I'm inheriting from User? (I can't test it yet because there are too many elements out of place elsewhere). Can I use the first version with 'user.username' instead though? Or, should I use the second version?

like image 507
orokusaki Avatar asked Feb 19 '10 16:02

orokusaki


2 Answers

I don't believe you can do what you're trying to do using django core. As pointed out in this answer to a related question unique_together is enforced at the DB layer. If you inspect the DB tables created by django model inheritance, you'll see this isn't possible for the DB to accomplish.

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

like image 176
Mike Fogel Avatar answered Sep 24 '22 15:09

Mike Fogel


It would be

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

if I understand what you're trying to do. Note the double underscore. That's how you look at a foreign key's object's properties.

like image 20
Tom Avatar answered Sep 21 '22 15:09

Tom