Django 数据库模型“unique_together”不工作?
我希望我的 ip
和 stream_id
组合是唯一的,所以我编写了这个模型:
# Votes
class Vote(models.Model):
# The stream that got voted
stream = models.ForeignKey(Stream)
# The IP adress of the voter
ip = models.CharField(max_length = 15)
vote = models.BooleanField()
unique_together = (("stream", "ip"),)
但由于某种原因它生成了这个表,跳过了 ip
mysql> SHOW CREATE TABLE website_vote;
+--------------+---------------------------------------------+
| Table | Create Table |
+--------------+---------------------------------------------+
| website_vote | CREATE TABLE `website_vote` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stream_id` int(11) NOT NULL,
`ip` varchar(15) NOT NULL,
`vote` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `website_vote_7371fd6` (`stream_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
+--------------+---------------------------------------------+
1 row in set (0.00 sec)
为什么密钥中不包含 ip
?作为记录,我知道可以在不嵌套元组的情况下编写 unique_together
行,但这与问题无关
I want my ip
and stream_id
combination to be unique, so I wrote this model:
# Votes
class Vote(models.Model):
# The stream that got voted
stream = models.ForeignKey(Stream)
# The IP adress of the voter
ip = models.CharField(max_length = 15)
vote = models.BooleanField()
unique_together = (("stream", "ip"),)
But for some reason it produces this table, skipping the ip
mysql> SHOW CREATE TABLE website_vote;
+--------------+---------------------------------------------+
| Table | Create Table |
+--------------+---------------------------------------------+
| website_vote | CREATE TABLE `website_vote` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stream_id` int(11) NOT NULL,
`ip` varchar(15) NOT NULL,
`vote` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
KEY `website_vote_7371fd6` (`stream_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
+--------------+---------------------------------------------+
1 row in set (0.00 sec)
Why doesn't it include ip
in the key? For the record I am aware that the unique_together
line can be written without nesting the tuples, but that has no bearing on the issue
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
unique_together
需要位于模型Meta
类中。请参阅文档。此外,还有一个内置的
IPAddressField
模型字段。请参阅此处的文档。unique_together
needs to be in the modelsMeta
class. See docs.Also, there's a builtin
IPAddressField
model field. See the docs here.