我有这个代码:
#api model
class VideoResource(ModelResource):
class Meta:
queryset = Video.objects.all()
include_resource_uri = False
resource_name = 'video'
authorization = DjangoAuthorization()
class QuestionResource(ModelResource):
user = fields.ToOneField(UserResource,'user',full=True)
video = fields.ForeignKey(VideoResource,'video',full=True)
class Meta:
queryset = Question.objects.all()
resource_name = 'question'
include_resource_uri = False
authorization = DjangoAuthorization()
def obj_create(self, bundle, request=None, **kwargs):
import json
temp = json.loads(request.body, object_hook=_decode_dict)
video = Video.objects.get(pk=temp['video'])
return super(QuestionResource, self).obj_create(bundle, request, user=request.user, video=video)
#model
class Question(models.Model):
text = models.CharField('Question',max_length=120)
created = models.DateTimeField(auto_now_add=True)
enabled = models.BooleanField(default=True)
flag = models.BooleanField(default=False)
allow_comments = models.BooleanField(default=True)
thumbnail_url = models.CharField(default='video.jpg',blank=True, null=True,max_length=200)
user = models.ForeignKey(User)
video = models.ForeignKey(Video)
def __unicode__(self):
return self.text;
class Video(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now_add=True)
url = models.URLField(default="")
user = models.ForeignKey(User)
def __unicode__(self):
return str(self.pk) + ' > ' + self.status
问题是我在发送此对象时收到此错误:
{"video":21,"text":"sadasds"}
'video' 字段的数据不是 URI,不是字典,也没有 'pk' 属性:21。
如果我评论这一行:
video = fields.ForeignKey(VideoResource,'video',full=True)
一切正常,但是在询问时我无法获得此信息(视频)/api/v1/questions/
我的问题是:
- 我应该创建资源,一个发布,另一个检索信息<-这似乎不是一个很好的解决方案。或者
- 如何创建嵌套资源?我尝试按照网络上的示例http://django-tastypie.readthedocs.org/en/latest/cookbook.html#nested-resources 但您可以看到由于某种原因无法正常工作。
也许你的眼睛可以帮助我找到错误:) 谢谢!