2011-09-23 95 views
2

我希望我的ipstream_id組合是唯一的,所以我寫了這個模式:Django數據庫模型「unique_together」不工作?

# 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行可以不嵌套元組而寫,但是這對問題沒有影響

回答

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