我正在尝试使用Tastypie工作创建新实例,但我不断使用外键获得此错误。这是我的东西:
型号:
class SuggestionVote(models.Model):
created_by_user = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now_add = True)
suggestion = models.ForeignKey(Suggestion)
class Suggestion(models.Model):
title = models.TextField(blank=True,null=True)
created_by_user = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now_add = True)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.title
模型资源(我使用自己的身份验证方法):
class UserResource(ModelResource):
class Meta:
list_allowed_methods = ['get']
queryset = User.objects.all()
resource_name = 'user'
authentication = MyBasicAuthentication()
authorization = DjangoAuthorization()
class SuggestionResource(ModelResource):
class Meta:
list_allowed_methods = ['get']
queryset = Suggestion.objects.all()
resource_name = 'suggestion'
authentication = MyBasicAuthentication()
authorization = DjangoAuthorization()
class SuggestionVoteResource(ModelResource):
class Meta:
list_allowed_methods = ['get', 'post']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
queryset = SuggestionVote.objects.all()
resource_name = 'suggestionvote'
authentication = MyBasicAuthentication()
authorization = DjangoAuthorization()
使用jQuery调用我的API:
var data = JSON.stringify({
"suggestion": "/api/suggestion/1/",
"created_by_user": "/api/user/1/"
});
$.ajax({
url: 'http://127.0.0.1:8000/api/suggestionvote/',
type: 'POST',
contentType: 'application/json',
data: data,
dataType: 'json',
processData: false
});
我得到的错误:
(1048,\“Column'created_by_user_id'不能为空\”)
我在这里错过了什么吗?
答案 0 :(得分:14)
我认为你需要的是关系领域的定义,这样的事情应该起作用:
from tastypie import fields
class SuggestionResource(ModelResource):
# the relationship
created_by_user = fields.ToOneField( UserResource, 'created_by_user', full = True )
class Meta:
list_allowed_methods = ['get']
queryset = Suggestion.objects.all()
resource_name = 'suggestion'
authentication = MyBasicAuthentication()
authorization = DjangoAuthorization()
我已经检查过,没有类似的字段定义,我得到的错误就像你的一样。
答案 1 :(得分:4)
这也有效。正如此Tastypie Tutorial
中所述from tastypie import fields
class SuggestionResource(ModelResource):
# the relationship
created_by_user = fields.ForeignKey( UserResource, 'created_by_user')
class Meta:
list_allowed_methods = ['get']
queryset = Suggestion.objects.all()
resource_name = 'suggestion'
authentication = MyBasicAuthentication()
authorization = DjangoAuthorization()