我正在使用tastypie为我的django项目快速创建一个api。我的Django包含一些模型,其中一个是客户模型。客户模型有一个django用户模型的外键,所以它看起来像这样
class Customer(models.Model):
...fields....
creator = models.ForeignKey(User, related_name='created_customers'
我创建了CustomerResource
class CustomerResourse(ModelResource):
creator = fields.ForeignKey(UserResource,'creator', null = True,
blank= True, full=True)
class Meta:
queryset = Customer.objects.all()
filtering = {
'last_name':ALL,
'first_name':ALL,
}
resource_name = 'customer'
authentication = SessionAuthentication()
authorization = DjangoAuthorization()
我希望能够使用api更新我的模型。阅读教程说它更新模型正在使用PUT。所以我的步骤是。
1)登录并获取sessionid 2)存储它 3)获得我需要的资源 4)修改我需要的资源 5)创建标题 6)使用requests.put将数据放回传递头和sessionid cookie。
代码(使用请求)
headers = {'content-type':'application/json'}
resp = requets.post(login_url, data=credentials, headers=headers)
sessionid = resp.cookies['sessionid']
cookies = {'sessionid':sessionid}
customer_json = request.get(customer_resource_url, cookies=cookies)
customer_json['mobile'] = 'new mobile'
resp.put(customer_resource_url, data=data, headers=headers, cookies=cookies)
我得到的是401未经授权的状态代码。用户是超级和工作人员,所以他可以修改一切。登录正常发生,我得到了我应该的sessionid。
还有第二个问题。如果我创建一个新客户,tastypie会处理外键,例如考虑到sessionid以确定用户创建者,还是需要手动完成?