Tastypie ManyToMany 中 POST / PUT 的错误

Errors with POST / PUT in Tastypie ManyToMany

我在使用 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()

Post函数:

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

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

如有任何帮助,我们将不胜感激。

问题是,您有 fields = ['rank_type']。 尝试 fields = ['rank_type', 'rank'] 应该可以。