我有以下资源,我试图覆盖obj_create。如果我不覆盖它,事情就会完美,但是当我覆盖它时会出现POST错误。任何线索?真的很感激答案虽然我相信tastypie真的没有得到任何堆栈溢出的答案这些天..这是非常烦人的。我正在考虑可能因为相同的原因而切换我的堆栈。
代码如下:
class OrderResource(BackBoneCompatibleResource):
person = fields.ToOneField(PersonResource, 'person', full=True)
restaurant = fields.ToOneField(RestaurantResource, 'restaurant', full=True)
itemList = fields.ToManyField(OrderItemResource, 'itemList', full=True)
class Meta:
object_class = Order
queryset = Order.objects.all().order_by("-time_updated")
resource_name = 'order'
allowed_methods = ['get','post','put','delete','patch']
authorization = Authorization()
serializer = Serializer(formats=['json', 'jsonp', 'xml', 'yaml', 'html', 'plist'])
authentication = ClientAuthentication()
authorization = OrderAuthorization()
always_return_data = True
filtering = {
"restaurant" : ["exact"],
"time_created" : ["gte"],
"person" : ["exact"]
}
def obj_create(self, bundle, request=None, **kwargs):
print "Entered Order Create"
return super(OrderResource, self).obj_create(bundle, request, **kwargs)
订单模型是:
class Order(models.Model):
restaurant = models.ForeignKey(Restaurant)
person = models.ForeignKey(Person)
tableNumber = models.CharField(max_length=2)
PLACED = 'p'
ACCEPTED = 'a'
READY = 'r'
ORDER_STATUS_CHOICES = (
(PLACED, 'Placed'),
(ACCEPTED, 'Accepted'),
(READY, 'Ready'),
)
order_status = models.CharField(max_length=1, choices=ORDER_STATUS_CHOICES, default=PLACED)
itemList = models.ManyToManyField(OrderItem, null=True)
tax = models.FloatField()
tip = models.FloatField()
cost = models.FloatField()
time_created = models.DateTimeField(auto_now_add=True)
time_updated = models.DateTimeField(auto_now=True)
正如我所说的,如果从资源中删除obj_create()函数,则发布正确。我只是编写文档中指定的默认函数,我无法理解我在做什么?我可能会遗漏一些非常明显的东西。谢谢你的时间..
我得到的具体错误如下,不确定它是否有多大帮助..
<type 'exceptions.TypeError'>, TypeError('obj_create() takes exactly 2 arguments (3 given)',), <traceback object at 0x10d30fb90>
答案 0 :(得分:4)
更改此行:
return super(OrderResource, self).obj_create(bundle, request, **kwargs)
对此:
return super(OrderResource, self).obj_create(bundle, request=request, **kwargs)
request
must be passed as a keyword argument。
答案 1 :(得分:2)
当您致电super().obj_create
时,您正在向父方法传递一个它并不期望的参数。错误消息告诉您错误,当您查看documentation中的父方法时,它会有意义。它会抓住**kwargs
,但看看有没有*args
?这意味着它无法处理您传递的request
参数。
Resource.obj_create(self, bundle, **kwargs) # Tastypie
我建议您使用相同的方法签名在您的子类上定义obj_create
,这样您就不会混淆调用者的期望。父母没有明确处理request
所以你也不应该这样做。最终代码:
class OrderResource(BackBoneCompatibleResource):
def obj_create(self, bundle, **kwargs):
print "Entered Order Create"
return super(OrderResource, self).obj_create(bundle, **kwargs)