Django数据库模型“unique_together”不起作用?

时间:2011-09-23 19:39:31

标签: mysql django model key unique

我希望我的ipstream_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行,但这与问题无关

1 个答案:

答案 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

相关问题