gpt4 book ai didi

Django 单元测试 : South-migrated DB works in MySQL, 在 PostGreSQL 中抛出重复的 PK 错误。我错过了什么还是这是一个错误?

转载 作者:行者123 更新时间:2023-11-28 21:15:00 25 4
gpt4 key购买 nike

(值得从免责声明开始:我是 PostGreSQL 的新手)

我有一个 Django 站点,其中包含一个标准的 app/tests.py 测试文件。如果我将数据库迁移到 MySQL(通过 South),测试全部通过。

但是在 PostGresQL 中,我收到以下错误:

IntegrityError: duplicate key value violates unique constraint "business_contact_pkey"

请注意,这仅发生在单元测试时 - 实际页面在 MySQL 和 PostGresql 中运行良好。

弄清楚这一点真的很费时间。有人有想法吗?以下是 Postgresql“\d business_contact”和违规的 tests.py 方法(如果有帮助的话)。除了(相同的)南迁移之外,没有对任何一个数据库进行任何更改

谢谢

 first_name   | character varying(200)   | not null
mobile_phone | character varying(100) |
surname | character varying(200) | not null
business_id | integer | not null
created | timestamp with time zone | not null
deleted | boolean | not null default false
updated | timestamp with time zone | not null
slug | character varying(150) | not null
phone | character varying(100) |
email | character varying(75) |
id | integer | not null default nextval('business_contact_id_seq'::regclass)
Indexes:
"business_contact_pkey" PRIMARY KEY, btree (id)
"business_contact_slug_key" UNIQUE, btree (slug)
"business_contact_business_id" btree (business_id)
Foreign-key constraints:
"business_id_refs_id_772cc1b7b40f4b36" FOREIGN KEY (business_id) REFERENCES business(id) DEFERRABLE INITIALLY DEFERRED
Referenced by:
TABLE "business" CONSTRAINT "primary_contact_id_refs_id_dfaf59c4041c850" FOREIGN KEY (primary_contact_id) REFERENCES business_contact(id) DEFERRABLE INITIALLY DEFERRED

测试防御:

   def test_add_business_contact(self):
""" Add a business contact """
contact_slug = 'test-new-contact-added-new-adf'
business_id = 1
business = Business.objects.get(id=business_id)
postdata = {
'first_name': 'Test',
'surname': 'User',
'business': '1',
'slug': contact_slug,
'email': 'test@example.com',
'phone': '12345678',
'mobile_phone': '9823452',
'business': 1,
'business_id': 1,
}

#Test to ensure contacts that should not exist are not returned
contact_not_exists = Contact.objects.filter(slug=contact_slug)
self.assertFalse(contact_not_exists)

#Add the contact and ensure it is present in the DB afterwards """
contact_add_url = '%s%s/contact/add/' % (settings.BUSINESS_URL, business.slug)
self.client.post(contact_add_url, postdata)
added_contact = Contact.objects.filter(slug=contact_slug)
print added_contact

try:
self.assertTrue(added_contact)
except:
formset = ContactForm(postdata)
print formset.errors
self.assertFalse(True, "Contact not found in the database - most likely, the post values in the test didn't validate against the form")

最佳答案

找到答案 - 我想我会把它留在这里留给后代。

在南方,我明确设置了数据迁移的主键 ID。 PGSQL 的排序器没有挑选它们,而是试图使用已经在数据迁移中设置的 PK 值。

从数据迁移中删除显式设置的主键值解决了这个问题。

关于Django 单元测试 : South-migrated DB works in MySQL, 在 PostGreSQL 中抛出重复的 PK 错误。我错过了什么还是这是一个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2888343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com