【发布时间】:2012-03-02 17:04:00
【问题描述】:
我正在尝试使用 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, \"列'created_by_user_id'不能为空\")
我错过了什么吗?
【问题讨论】:
-
你也有用户资源吗?
-
我正在使用 django-registration 并且只有一个 UserProfile 模型,它只是一对一地映射到用户
-
Tastypie 适用于资源而不是模型,因此“/api/user/1/”要指向用户,您还需要一个用户资源,模型是不够的。我希望这会有所帮助:)
-
我有一个用户资源,但它仍然不起作用。我已经在问题中更新了这个
-
你在这方面有什么进展吗??我还希望将 django-registration 与 sweetpie 集成