Django Tastypie:OneToOneField嵌套资源和Post Save冲突

时间:2015-08-08 23:12:18

标签: python django tastypie

我有两个模型:UserUserProfile。 用户是django.contrib.auth.models,它与UserProfile具有一对一的关系

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    mobile = models.CharField(max_length=10)
    address = models.TextField()

此外,在创建User时,使用Post Save Hook on User创建UserProfile。

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = UserProfile.objects.get_or_create(user=instance)

我正在尝试使用Tastypie创建新用户。这是我的代码:

class UserProfileResource(ModelResource):
user = fields.OneToOneField('app.api.UserResource', 'user', full=True)

class Meta:
    always_return_data = True
    authentication = authentication()
    authorization = authorization()
    queryset = UserProfile.objects.all()
    fields = ['mobile', 'address']
    always_return_data = True

def dehydrate(self, bundle, **kwargs):
    userb = bundle.data['user']
    del userb.data['password']
    return bundle    



class UserResource(ModelResource):
    class Meta:
        authentication = Authentication()
        authorization = Authorization()
        queryset = User.objects.all()
        excludes = ['is_active', 'is_staff', 'is_superuser', 'date_joined',
                    'last_login']

    def hydrate(self, bundle):
        raw_password = bundle.data["password"]
        bundle.data['password'] = make_password(raw_password)
        return bundle

现在,如果我对用户发布保存挂钩,并以下列格式发布数据,那么一切正常。

{"user": {"email": "test@test.com", "first_name": "test123", "last_name": "test1234", "username": "test", "password": "1234"}, "mobile": "1983", "address": "dummy  address"}

Post Save挂钩在这里引起问题,因为在创建User时,已经创建了用户个人资料,Tastypie正在提供IntegrityError

(1062, "Duplicate entry '36' for key 'user_id'")

我无法删除post save hook,还必须创建User&用户配置文件在单个端点使用API​​。

请帮我把post_save挂钩和Tastypie一起工作。我准备修改post_save hook,UserProfile save override和Tastypie Resources来实现这一点。

注意:我在Django 1.6,Python 2.7,django-tastypie 0.12.1

谢谢!

0 个答案:

没有答案