考虑一个干净的 django 1.7.7 项目,其中包含一个名为 testrunner 的应用程序。
模型如下所示:
class Contact(AbstractBaseUser, PermissionsMixin, models.Model):
relation = models.ForeignKey('tests.Relation', related_name='contacts')
username = models.CharField(max_length=200, unique=True)
first_name = models.CharField(max_length=30, null=True, blank=True)
last_name = models.CharField(max_length=30, null=True, blank=True)
email = models.EmailField(null=True, blank=True, unique=True)
is_staff = models.BooleanField('staff status', default=False,
help_text='Designates whether the user can log into this admin site.')
is_active = models.BooleanField('active', default=True,
help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.')
USERNAME_FIELD = 'username'
def get_full_name(self):
pass
def get_short_name(self):
pass
def get_name(self):
pass
class Relation(models.Model):
name = models.CharField(max_length=200, unique=True)
created_by = models.ForeignKey('tests.Contact', null=True, related_name='created_%(class)s')
modified_by = models.ForeignKey('tests.Contact', null=True, related_name='modified_%(class)s')
def natural_key(self):
return (self.name,)
在 settings.py 中,我已将 'tests.Contact'
设置为 AUTH_USER_MODEL
。
此设置是一个干净的测试,用于复制我在更大的环境中遇到的错误。问题是,如果创建测试数据库失败,我就无法运行 django 测试:
manage.py test
Testing started at 14:39 ...
Creating test database for alias 'default'...
CommandError: Can't resolve dependencies for tests.Contact, admin.LogEntry, tests.Relation in serialized app list.
Process finished with exit code 1
Empty test suite.
当我从关系模型中删除 def natural_key(self)
时,一切正常。
我们希望在我们的装置的关系模型上使用natural_key,但无法使其与 django 测试一起使用。
我做错了什么?
最佳答案
一个非常简单的解决方案,但我花了一些时间才想出来。
tl;博士
- 动态导入序列化器。
- 动态定义natural_keys方法并分配给模型。
def method_where_serializers_is_being_used():
# import serlializers
from django.core import serializers
# define natural_key method
def natural_key(self):
return some_unique_id
DjangoModel.natural_key = natural_key
这是一种黑客行为,但工作正常
关于python - Natural Key 导致 Django 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29629853/