python - Tastypie - 找不到嵌套资源字段

标签 python django tastypie

我有这个代码:

#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"} 

“视频”字段被赋予的数据不是 URI,不是 类似字典且没有“pk”属性:21.

如果我评论这一行:

video = fields.ForeignKey(VideoResource,'video',full=True) 

一切正常,但我无法获取此信息(视频) 当询问 /api/v1/questions/

我的问题是:

也许你的眼睛可以帮我找出错误:) 谢谢!

最佳答案

The 'video' field has was given data that was not a URI, not a dictionary-alike and does not have a 'pk' attribute: 21.

所以,这意味着整数 21 不满足该字段的要求,它也给出了一个模糊的提示,表明什么会满足要求。

首先,您可以发送 URI 进行记录,这可能是最正确的方法,因为 URI 确实是唯一的,而 pk 则不是。

{"video":"/api/v1/video/21","text":"sadasds"} 

或者,您可以发送一个带有 pk 字段集的类似字典的对象。

{"video":{'pk':21},"text":"sadasds"} 

当您注释掉 ForeignKey 字段时它起作用的原因是因为 tastypie 将其视为 IntegerField,可以由普通整数引用。

这让我迟钝了一段时间,希望对您有所帮助!

关于python - Tastypie - 找不到嵌套资源字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10242494/

相关文章:

django - 注释字段的Django Queryset绝对值

python - 为什么在 Django 中重写 Model.save() 函数不起作用?

angularjs - REST方式批量更新、创建、删除

python - 用时间桶对 Python 中的数据进行分组

Django:从抽象模型继承权限?

python - 在带有 IN sql 语句的 pymssql 中使用 cursor.execute 参数

django - 如何以编程方式使用django-tastypie API创建或注册用户?

django - Django Tastypie 中 'obj_get' 的正确实现是什么?

python - 为什么 scipy 稀疏矩阵内存使用对矩阵中元素的数量无动于衷?

python - 返回 numpy 数组的函数上的 scipy.integrate.quad