2011-07-13 37 views
1
class A(models.Model): 
    title = models.CharField(max_length=240,null=True, blank=True, db_index=True) 
    body = models.TextField(blank=True, null=True) 
    adinfo = models.CharField(max_length=240, null=True, blank=True, db_index=True) 
    url = models.CharField(max_length=10000, null=True,blank=True) 
    img = models.CharField(max_length=10000, null=True,blank=True) 
    created_at = models.DateTimeField(auto_now_add=True, null=True, db_index=True) 
    updated_at = models.DateTimeField(auto_now=True, null=True) 
    class Meta: 
     unique_together = (('title','adinfo'),) 


mysql> select * from mo_a where id = 1113\G; 
*************************** 1. row *************************** 
     id: 1113 
    title: Tides Tavern 
     body: Come in and enjoy the morning sun or a nice sunset with breakfast, lunch or dinner. Find a seat, put your feet up & enjoy. Click here! 
    adinfo: NULL 
     url: 
     img: http://creative.ak.fbcdn.net/v41818/flyers/125/47/13039135731061564765_1_89254352.jpg 
created_at: 2011-07-08 00:41:18 
updated_at: 2011-07-08 00:41:18 
1 row in set (0.00 sec) 

ERROR: 
No query specified 

mysql> select * from mo_a where id = 1114\G; 
*************************** 1. row *************************** 
     id: 1114 
    title: Tides Tavern 
     body: Come in and enjoy the morning sun or a nice sunset with breakfast, lunch or dinner. Find a seat, put your feet up & enjoy. Click here! 
    adinfo: NULL 
     url: 
     img: http://creative.ak.fbcdn.net/v41818/flyers/125/47/13039135731061564765_1_89254352.jpg 
created_at: 2011-07-08 00:41:22 
updated_at: 2011-07-08 00:41:22 
1 row in set (0.00 sec) 

ERROR: 
No query specified 

這是正常的嗎?正如你所看到的,我擁有獨一無二的title和adinfo ......我不想讓#1114被插入。但它的確如此。如何刪除數據庫中的所有重複項?Django如何進來,unique不起來?

+0

您的問題是關於如何在Django中強制實施唯一性約束,或者如何在MySQL中刪除大量重複項?如果你想要兩個問題的答案,你應該問第二個問題的重複刪除(檢查之後,看看它之前是否被問過)。 –

+0

你試過adinfo不是NULL嗎?只是出於好奇,因爲無論您通過數據庫重複多少次,django都會將「NULL」值視爲獨特值。所以也許這會導致一些問題......只是做一個測試填充adinfo字段 –

+2

「[對於所有引擎,UNIQUE索引允許多個NULL值用於包含NULL的列](http://dev.mysql.com/doc /refman/5.1/en/create-index.html)」。 – DrTyrsa

回答

1

您指定UNIQUE約束的方式,您聲明不允許插入對的重複項。

當你指定,你將能夠插入對:

(1113, 'Tides Tavern') and (1114, 'Tides Tavern') 

(1113, 'Roman road') and (1113, 'Tides Tavern') 

但不是:

(1113, 'Tides Tavern') and (1113, 'Tides Tavern') 

換句話說,從PostgreSQL的文檔: 「多列唯一索引只會拒絕所有索引列ar兩行相等。「