在我的应用程序中,我想在新用户注册时在某些表中创建条目.例如,我想创建一个userprofile,然后引用他们的公司和其他一些记录.我用post_save信号实现了这个:
def callback_create_profile(sender, **kwargs):
# check if we are creating a new User
if kwargs.get('created', True):
user = kwargs.get('instance')
company = Company.objects.create(name="My Company")
employee = Employee.objects.create(company=company, name_first=user.first_name, name_last=user.last_name)
profile = UserProfile.objects.create(user=user, employee=employee, partner=partner)
# Register the callback
post_save.connect(callback_create_profile, sender=User, dispatch_uid="core.models")
Run Code Online (Sandbox Code Playgroud)
运行时效果很好.我可以使用admin创建一个新用户,其他三个表也可以获得合理的条目.(除此之外,员工因为user.first_name和user.last_name在保存时未在管理员表单中填写.我仍然不明白为什么这样做)
当我运行我的测试套件时出现问题.在此之前,我创建了一堆灯具来在表格中创建这些条目.现在我收到一条错误,指出:
IntegrityError: duplicate key value violates unique constraint "core_userprofile_user_id_key"
Run Code Online (Sandbox Code Playgroud)
我想这是因为我已经在id为"1"的灯具中创建了公司,员工和个人资料记录,现在post_save信号正在尝试重新创建它.
我的问题是:我可以在运行灯具时禁用此post_save信号吗?我可以检测到我作为测试套件的一部分运行而不是创建这些记录吗?我现在应该从灯具中删除这些记录吗(虽然信号只设置默认值而不是我想要测试的值)?为什么夹具加载代码不会覆盖创建的记录?
人们如何做到这一点?
我正在使用Saleor/Satchless来支持电力和电子商务网站(继承了该项目).我找不到Saleor邮件列表,所以在此发帖.
./manage.py dumpdata -e contenttypes -e sessions -e south -e > payments_data.json
当我运行测试并且django尝试加载灯具时,它会解决这个问题.我使用Postgres作为数据库,虽然不是很熟悉,但似乎可能存在加载数据的顺序问题
任何想法如何解决它?
======================================================================
ERROR: test__hometryon_extra_pair_sizes (payment.tests.InterstitialTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/andres/.virtualenvs/rpmwest/lib/python2.7/site-packages/django/test/testcases.py", line 259, in __call__
self._pre_setup()
File "/Users/andres/.virtualenvs/rpmwest/lib/python2.7/site-packages/django/test/testcases.py", line 479, in _pre_setup
self._fixture_setup()
File "/Users/andres/.virtualenvs/rpmwest/lib/python2.7/site-packages/django/test/testcases.py", line 849, in _fixture_setup
'skip_validation': True,
File "/Users/andres/.virtualenvs/rpmwest/lib/python2.7/site-packages/django/core/management/__init__.py", line 161, in call_command
return klass.execute(*args, **defaults)
File "/Users/andres/.virtualenvs/rpmwest/lib/python2.7/site-packages/django/core/management/base.py", line 255, in execute
output = self.handle(*args, **options)
File "/Users/andres/.virtualenvs/rpmwest/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 224, in handle
connection.check_constraints(table_names=table_names)
File "/Users/andres/.virtualenvs/rpmwest/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", …
Run Code Online (Sandbox Code Playgroud)