2016-03-26 47 views
1

我有延伸的Django 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或社交網絡中)。 但我想用在我的tastypie資源中。我有兩個資源:

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位於UserProfile模型而不是User模型,因此關聯的資源字段應繼續使用UserProfileResource而不是UserResource

在任何情況下,我建議將contact放在自定義用戶對象上,而不是配置文件模型;它會簡化您的代碼並保存數據庫連接,如果您將與用戶相關的所有內容都關聯到與用戶相關的表。

+0

如果我把'contacts'字段放在'UserProfileResource'中,並且在調用一個Python對象_時出錯_maximum遞歸深度超出了,它就不起作用。 – Gooman

+0

也許你可以使用自定義用戶對象建議一些決定? – Gooman

+0

哦,我錯過了'contact'實際上使用'UserProfileResource',它應該使用'UserResource',因爲'contacts'是用戶模型中的m2m,而不是UserProfile模型。 –

0

contacts是在UserProfile,而不是在UsercontactsUser類型,而不是UserProfile

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

如果你真的需要UserProfile,嘗試:

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

,但我不能保證它會工作。這只是想法。