我正在创建 UserResource 和 UserProfileResource。当我创建一个新用户时,我看到我的 userprofile 数据库表也在更新。哪个好。但是当我 GET 用户时,我收到一条错误消息:
The model '' has an empty attribute 'profile' and doesn't allow a null value.
我的代码:
资源.py
class UserProfileResource(ModelResource):
home_address = fields.CharField(attribute='home_address')
user = fields.ToManyField('resources.UserResource', attribute='user', related_name='profile')
class Meta:
queryset = UserProfile.objects.all()
resource_name = 'profile'
allowed_methods = ['get', 'post', 'delete', 'put']
fields = ['home_address']
authorization = Authorization()
include_resource_uri = False
include_absolute_url = False
class UserResource(ModelResource):
profile = fields.ToOneField('resources.UserProfileResource', attribute = 'profile', related_name='user', full=True)
class Meta:
queryset = User.objects.all()
resource_name = 'user'
allowed_methods = ['get', 'post', 'delete', 'put']
fields = ['username']
filtering = {
'username': ALL,
}
authorization = Authorization()
def obj_create(self, bundle, request=None, **kwargs):
try:
bundle = super(UserResource, self).obj_create(bundle, request, **kwargs)
bundle.obj.set_password(bundle.data.get('password'))
bundle.obj.save()
except IntegrityError:
raise BadRequest('IntegrityError')
return bundle
模型.py
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
home_address = models.TextField()
有人有什么想法吗?约翰诺克