Python 是否可以使用Django';什么样的固定装置?
我在测试中使用了Django的装置。我需要创建UserProfile fixture。第一个问题是它指向用户条目。为了解决这个问题,我使用了自然键。所以我只说UserProfile fixture的user字段是user fixture的实际用户名Python 是否可以使用Django';什么样的固定装置?,python,django,json,unit-testing,fixtures,Python,Django,Json,Unit Testing,Fixtures,我在测试中使用了Django的装置。我需要创建UserProfile fixture。第一个问题是它指向用户条目。为了解决这个问题,我使用了自然键。所以我只说UserProfile fixture的user字段是user fixture的实际用户名 [ { "pk": 8002, "model": "auth.user", "fields": { "date_joined": "2012-08-28 10:00:00
[
{
"pk": 8002,
"model": "auth.user",
"fields": {
"date_joined": "2012-08-28 10:00:00.000000+00:00",
"email": "",
"first_name": "",
"groups": [],
"is_active": true,
"is_staff": false,
"is_superuser": false,
"last_login": "2012-08-28 10:00:00.000000+00:00",
"last_name": "",
"password": "pbkdf2_sha256$10000$ltmEKsdCPjuK$74ZwNUh8rqFAPZ6+Cmi3tc8A94ueeXTplFqOQKlY4hc=",
"user_permissions": [],
"username": "user8002"
}
},
{
"pk": null,
"model": "spam_and_eggs.userprofile",
"fields": {
"user": ["user8002"],
"language": "",
"email_activated": true
}
}
]
不幸的是,它返回了一个错误:
IntegrityError: Could not load share4you.UserProfile(pk=None): column user_id is not unique
第二个问题来了。我认为它可能会失败,因为当使用Django的信号创建用户时,会自动创建UserProfile,而fixture会失败,因为已经创建了该用户的UserProfile。这可能是原因吗?有没有办法解决这个问题
谢谢你的建议
编辑#1:
型号和信号:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
language = models.CharField(max_length=255, null=True, blank=True)
email_activated = models.BooleanField()
@receiver(post_save, sender=User)
def create_profile(instance, created, **kwargs):
if created:
UserProfile.objects.get_or_create(user=instance)
用户模型是django.contrib.auth.models.User
是否可以使用Django的设备更改现有数据
当然,如果一个fixture在数据库中有一个pk,django将进行更新
user=models.ForeignKey(user,unique=True)
这很有趣,为什么在这种情况下不使用OneToOneField呢
>>> a=User.objects.all()[0]
>>> a.userprofile_set.all()
[<UserProfile: UserProfile object>]
>> a.userprofile_set.create(language='bar')
IntegrityError: column user_id is not unique
另外,这里还有另一种可能,可以创建一个UserProfile类,其中包括:
您可以在创建配置文件中检查原始参数。它表明,如果它来自夹具或不是,检查更多细节。通过这种方式,您可以控制配置文件的创建。我建议您也查看一下。这将使您的数据看起来像夹具,但更“智能”一点。您可以发布您的模型和信号接收器吗?谢谢,这就成功了!此外,它不是一对一的关系,因为用户可以有许多配置文件。:)一个用户只能有一个配置文件,因为UserProfile.User是唯一的!为了澄清这句话:“当然,如果一个fixture在数据库中有一个pk,django将进行更新”,为了清楚起见,我会添加一个,只要您指定字段。如果你不这样做,django会把他们清除掉。
[
{
"pk": 1,
"model": "auth.user",
"fields": {
"username": "jpic",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2012-06-11T06:44:57.637Z",
"groups": [],
"user_permissions": [],
"password": "pbkdf2_sha256$10000$KzsUTACvZgJU$qvywXdVv/N3s5lifS/gQxSGog36ExGbuj2U+IQ6aUNk=",
"email": "t@tt.tt",
"date_joined": "2012-06-11T06:44:57.637Z"
}
},
{
"pk": 1,
"model": "test_app.userprofile",
"fields": {
"language": "example.com",
"user": 1
}
}
]
from annoying.fields import AutoOneToOneField
class UserProfile(models.Model):
user = AutoOneToOneField('auth.User', primary_key=True)
home_page = models.URLField(max_length=255, blank=True)