Tastypie发送POST以更新外键

时间:2018-05-22 15:21:48

标签: python django post tastypie

我最近开始使用Django(和python一般!),我希望使用Tastypie来自动添加数据库。

对于我当前的问题,我的数据库中有两个表,一个显示公司名称和公司ID,另一个包含所有许可证密钥信息,如下所示:

models.py

class Company(models.Model):
    company_name = models.CharField(max_length=200, verbose_name= "Company Name")
    company_id = models.CharField(max_length=15, verbose_name= "Company ID")

    def __str__(self):
        return self.company_name


class Licence(models.Model):
    company_id = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name= "Company ID")
    licence_key = models.CharField(max_length=100, verbose_name= "Licence Key")
    lpars = models.CharField(max_length=100, default = "", verbose_name= "List of Systems")
    rss = models.BooleanField(default = None, verbose_name= "RSS")
    gui = models.BooleanField(default = None, verbose_name= "RACFGui")
    exr = models.BooleanField(default = None, verbose_name= "Exception Reporter")
    zdt = models.BooleanField(default = None, verbose_name= "zDetect")
    bg = models.BooleanField(default = None, verbose_name= "BreakGlass")
    sspr = models.BooleanField(default = None, verbose_name= "Self Service Password Reset")
    rss_custom = models.BooleanField(default = None, verbose_name= "RSS Custom")
    expiry = models.DateField(auto_now=False, auto_now_add=False)
    trial = models.BooleanField(default = False, verbose_name= "Trial?")

    def __str__(self):
        return self.licence_key

然后我在这里定义了所有的api内容:

resources.py

class CompanyResource(ModelResource):
    class Meta:
        queryset = Company.objects.all()
        resource_name = 'company'

class LicenceResource(ModelResource):

    class Meta:
        queryset = Licence.objects.all()
        include_resource_uri = True
        resource_name = 'licence'
        authorization = Authorization()
    def dehydrate(self, bundle):
        bundle.data['company'] = bundle.obj.company_id
        return bundle

当我发出GET请求时,这很有效,并显示以下信息:

{
"bg": false,
"company": "xxxx", (blanked out for security)
"expiry": "2018-05-11",
"exr": true,
"gui": false,
"id": 13,
"licence_key": "xxxxx-xxxxx-xxxxx",
"lpars": "xxxx xxxx",
"resource_uri": "/api/licence/13/",
"rss": true,
"rss_custom": true,
"sspr": false,
"trial": false,
"zdt": true

}

然而,当我尝试使用POST request复制时,我得到了

  

" error_message":" NOT NULL约束失败:licence_licence.company_id_id"

我知道我还没有使用POST请求提交此值,但我认为_id是数据库条目的ID,通常由Django自动管理。

有没有办法让这个由Django管理,如果省略,或者是否有更聪明的方式来格式化POST请求?

非常感谢你的时间!这是我关于SO的第一篇文章,所以如果我省略了什么,请告诉我:)

0 个答案:

没有答案