1

私は UserProfile クラスを持っています:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    bio = models.CharField(max_length=180, null=True)

それは User クラスにリンクされています。

AUTH_PROFILE_MODULE = 'plantvillage.userprofile'

ユーザーの詳細とユーザープロファイルの詳細を同時に管理できるように、tastypie を通じて 1 つの API を提供したいと考えています。可能であれば、2 つのインターフェイス (ユーザー用とユーザー プロファイル用) を公開したくありません。

リソースを次のように設定しました。

class ProfileResource(ModelResource):
    class Meta:
        queryset = UserProfile.objects.all()
        resource_name = 'profile'
        authentication = ApiKeyAuthentication()
        authorization = DjangoAuthorization()
        allowed_methods = ['get', 'put', 'patch']

class UserResource(ModelResource):
    profile = fields.ToOneField(ProfileResource, 'userprofile', full=True)

    class Meta:
        queryset = User.objects.filter(is_staff=False)
        resource_name = 'usr'
        authentication = ApiKeyAuthentication()
        authorization = DjangoAuthorization()

        excludes = ['password', 'is_active', 'is_staff']

ただし、アップデート

curl --dump-header - -H "Authorization: ApiKey abc6@abc.com:1432ece6a1f34fae24a77315b5c924f756f13807" -H "Content-Type: application/json" -X PATCH --data '{"profile":{"bio":"aquarium"}}' "http://127.0.0.1:8000/api/usr/25/"

次のエラーが発生します。

"error_message": "duplicate key value violates unique constraint \"plantvillage_userprofile_user_id_key\"\n", "traceback": "Traceback (most recent call last):\n\n  File \"/usr/local/lib/python2.6/dist-packages/django_tastypie-0.9.12_alpha-py2.6.egg/tastypie/resources.py\", line 196, in wrapper\n

これを機能させるには、どのような変更を加えることができますか?

4

1 に答える 1

2

次のように、完全に削除して、公開したいモデルUserResourceからフィールドを追加できます。User

username = fields.CharField( attribute = 'user__username' )

Userこれは、GET リクエストの場合にモデルから適切なデータを送信するだけでなく、更新も処理します。

于 2012-09-05T03:06:48.910 に答える