gpt4 book ai didi

django - Tastypie Foreignkey设置为null

转载 作者:行者123 更新时间:2023-12-04 13:24:11 25 4
gpt4 key购买 nike

我正在创建UserResource和UserProfileResource。当我创建一个新用户时,我看到我的用户配置文件数据库表也正在更新。哪个好但是当我得到用户时,我得到一个错误,说:

The model '' has an empty attribute 'profile' and doesn't allow a null value.

我的代码:

resources.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

models.py
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
home_address = models.TextField()

有人有想法吗?
约诺克

最佳答案

经过大量的搜索,我终于得到了答案。

models.py

class UserProfile(models.Model):
user = models.OneToOneField(User)
home_address = models.TextField()

resources.py
class UserProfileResource(ModelResource):
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 = 'userprofile', related_name='user', full=True, null=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

这行得通。请注意,模型字段已更改为OneToOneField,并且资源属性现在为“userprofile”。我希望这对外面的人有所帮助!

约翰

关于django - Tastypie Foreignkey设置为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10603300/

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