我希望我的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
行,但这与问题无关
答案 0 :(得分:6)
unique_together
需要位于模型Meta
类中。请参阅docs。
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()
class Meta:
unique_together = (("stream", "ip"),)
此外,还有一个内置IPAddressField
模型字段。请参阅文档here。