gpt4 book ai didi

Django Deliciouspie是否创建具有外键的新资源?

转载 作者:行者123 更新时间:2023-12-04 03:09:12 24 4
gpt4 key购买 nike

我正在尝试使用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' cannot be null\")



我在这里想念什么吗?

最佳答案

我认为您需要的是关系字段的定义,类似这样的方法应该起作用:

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()

我已经检查过,并且没有类似的字段定义,但是我得到一个和您一样的错误。

关于Django Deliciouspie是否创建具有外键的新资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9537355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com