Django unique_together on sub-class model for parent attribute?

后端 未结 3 2167
青春惊慌失措
青春惊慌失措 2021-02-19 10:43

In this:

class Administrator(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    account = models.ForeignKey(Account)

    class Meta:
            


        
相关标签:
3条回答
  • 2021-02-19 10:48

    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.

    0 讨论(0)
  • 2021-02-19 11:01

    What you are missing is abstract = True in the base class. This creates a table with all the fields for the subclass.

    0 讨论(0)
  • 2021-02-19 11:08

    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.

    0 讨论(0)
提交回复
热议问题