Django unique_together在父类属性的子类模型上?

[英]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:

self.user.username部分显然是不正确的。但是,在这:

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?

那是因为我从用户那里继承了吗? (我还不能测试它,因为其他地方有太多元素不合适)。我可以使用带有'user.username'的第一个版本吗?或者,我应该使用第二个版本吗?

2 个解决方案

#1


8  

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.

如果我明白你要做什么请注意双下划线。这就是你如何看待外键对象的属性。

#2


6  

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.

我不相信你可以使用django核心做你想做的事情。正如在相关问题的答案中所指出的,unique_together在DB层强制执行。如果检查由django模型继承创建的数据库表,您将看到数据库无法完成此操作。

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

对于某些替代解决方案,请查看相关问题。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2010/02/19/164ddb68fe658a835a9ab9dfefb2302d.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号