【发布时间】:2011-07-13 11:44:23
【问题描述】:
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
这正常吗?如您所见,我有唯一的标题和广告信息...我不想插入#1114。但确实如此。如何删除数据库中的所有重复项?
【问题讨论】:
-
您的问题是关于如何在 Django 中强制执行唯一性约束,或者如何在 MySQL 中删除大量重复项?如果您想知道这两个问题的答案,您应该针对重复删除提出第二个问题(在检查之前是否有人问过该问题之后)。
-
您是否尝试过使用不为 NULL 的 adinfo?只是出于好奇,因为无论您在数据库中重复多少次,django 都将“NULL”值视为唯一值。所以也许它会导致一些问题......只需做一个填充 adinfo 字段的测试
-
DrTyrsa 是对的。 MySQL 并不认为 NULL 和 NULL 一样,所以就它而言,唯一索引是满足的。在 MySQL 的世界中,title != title, adinfo != adinfo,因此没有违反唯一性约束。
标签: python mysql database django