2016-03-26 9 views
1

私はジャンゴUserモデルを拡張したモデルがあります:あなたが見ることができるようにTastyPie:ToManyField関連リソース

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    avatar = models.CharField(max_length=40, default='0') 
    activation_key = models.CharField(max_length=40, blank=True) 
    key_expires = models.DateTimeField(default=django.utils.timezone.now) 
    contacts = models.ManyToManyField(User, related_name='contacts') 

、フィールドcontactsがあります。このフィールドを使用すると、すべてのユーザーが連絡先のリスト(Skypeやソーシャルネットワークなど)を持つことができます。 しかし、私はそれを自分の才能のあるリソースに使いたいです。私は2つのリソースを持っています:

class UserProfileResource(ModelResource): 
    class Meta: 
     queryset = UserProfile.objects.all() 
     authentication = SessionAuthentication() 
     authorization = DjangoAuthorization() 
     allowed_methods = ['get'] 
     resource_name = 'profile' 
     excludes = ['id'] 
     include_resource_uri = False 

class UserResource(ModelResource): 
    userprofile = fields.ToOneField(UserProfileResource, 'userprofile', null=True, full=True) 
    contacts = fields.ToManyField(UserProfileResource, 'contacts', related_name='contacts', null=True, full=True) 

    class Meta: 
     queryset = User.objects.all() 
     fields = ['first_name', 'last_name', 'email', 'date_joined', 'last_login', 'userprofile', 'contacts'] 
     allowed_methods = ['get', 'post', 'patch'] 
     resource_name = 'user' 
     detail_uri_name = 'username' 
     authentication = SessionAuthentication() 
     authorization = DjangoAuthorization() 

私はGET要求をすると、フィールドの連絡先はうまくいきません。私はTastyPieリソースの連絡先フィールドに他のユーザーのリストを表示する方法を理解できません。ちなみに、Djangoの管理ページでは私は連絡先のリストを見ることができ、私はそれを編集することができます。

このように、tastypieリソースを実現することで、現在のユーザーを自分の連絡先リストに追加したユーザーの一覧を取得することができます。しかし、私は現在のユーザーの連絡先のリストが必要です。私は間違っている?

答えて

0

contactsはUserモデルではなくUserProfileモデルにあるため、関連するリソースフィールドはUserResourceの代わりにUserProfileResourceになるはずです。

いずれにしても、私はcontactをプロファイルモデルではなくカスタムUserオブジェクトに配置することをおすすめします。 Userに関連するテーブルに関連するのではなく、Userに関連するものをすべて作成すると、コードを単純化してDBジョインを節約できます。

+0

Pythonオブジェクト_を呼び出しているときに_maximum再帰深度を超過した 'UserProfileResource'フィールドに' contacts'フィールドを置くと動作しません。 – Gooman

+0

カスタムユーザーオブジェクトを使用していくつかの決定を提案できますか? – Gooman

+0

ああ、 '連絡先'が実際に 'UserProfileResource'を使うのを忘れました。' Contacts'はUserProfileモデルではなくUserモデル上のm2mなので、 'UserResource'を使うべきです。 –

0

contactsUserProfileではなく、UsercontactsであるUserタイプではなく、UserProfileです:あなたは本当にUserProfileが必要な場合は

contacts = fields.ToManyField(UserResource, 'userprofile__contacts', related_name='contacts', null=True, full=True) 

、試してみてください。

contacts = fields.ToManyField(UserProfileResource, 'userprofile__contacts__userprofile', related_name='contacts', null=True, full=True) 

が、私はそれを保証することはできませんそれが動作します。それは唯一のアイデアです。

関連する問題