我有延伸的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資源的這種實現可以獲取在自己的聯繫人列表中添加當前用戶的用戶列表。但我需要當前用戶的聯繫人列表。我做錯了什麼?
如果我把'contacts'字段放在'UserProfileResource'中,並且在調用一個Python對象_時出錯_maximum遞歸深度超出了,它就不起作用。 – Gooman
也許你可以使用自定義用戶對象建議一些決定? – Gooman
哦,我錯過了'contact'實際上使用'UserProfileResource',它應該使用'UserResource',因爲'contacts'是用戶模型中的m2m,而不是UserProfile模型。 –