Tastypie ManyToMany中的POST / PUT错误

时间:2015-12-26 15:07:30

标签: python django tastypie

我在使用ManyToMany和Tastypie发布和放置数据时收到错误。 我花了几个小时试图自己解决这个问题并审核了以下帖子:

IAPP / models.py

class Rankings(models.Model):

    rank_type = models.CharField(max_length=120,default='',blank=True,null=True)    
    rank = models.IntegerField()
    ranking_domain = models.CharField(max_length=120,default='',blank=True,null=True)
    ranking_url = models.CharField(max_length=120,default='',blank=True,null=True)

class Keyword(models.Model):

    keyword = models.CharField(max_length=120,default='',blank=True,null=True)
    u_ts = models.DateTimeField(auto_now_add=True,auto_now=False)
    state = models.CharField(max_length=120,default='',blank=True,null=True)
    s_ts = models.DateTimeField(blank=True,null=True)
    ip = models.CharField(max_length=120,default='',blank=True,null=True)
    rankings = models.ManyToManyField(Rankings,blank=True)

IAPP / API / resources.py

class KeywordResource(ModelResource):   
    rankings = fields.ToManyField('iapp.api.resources.RankingsResource', 'rankings',null=True, full=True)
    class Meta:
        queryset = Keyword.objects.all()
        resource_name = 'keyword'
        allowed_methods = ['get','post','put','patch']
        authentication = ApiKeyAuthentication()
        authorization = DjangoAuthorization()
        filtering = {"keyword": ('exact', 'startswith',),
                     "state": ('exact',)}

class RankingsResource(ModelResource):

    class Meta:
        queryset = Rankings.objects.all()
        resource_name = 'rankings'
        fields = ['rank_type']
        allowed_methods = ['get','post','put','patch']
        authentication = ApiKeyAuthentication()
        authorization = DjangoAuthorization()

发布功能:

def add_keyword(self,**kwargs): 

    keyword = kwargs['keyword']     
    data = {"keyword": keyword,
            "u_ts":None,
            "state":"added",
            "s_ts":None,
            "ip":None,
            "rankings":[{"rank_type":'typetest',
                                        "rank":0,
                                        "ranking_domain":'domaintest',
                                        "ranking_url":'urltest'}]
            } 

    req_post = requests.post(self.endpoints['keywords'],#dict for different endpoints
                             headers=self.headers,#my authentication
                             data=json.dumps(data)) 

错误:

NOT NULL constraint failed: iapp_rankings.rank

但是,数据(减去排名数据)会添加到数据库中。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

问题是,你有fields = ['rank_type']。 试试fields = ['rank_type', 'rank'],它应该有用。