Search code examples
pythondjangotastypie

Errors with POST / PUT in Tastypie ManyToMany


I'm receiving an error when posting and putting data using ManyToMany with Tastypie. I've spent a few hours trying to figure it out on my own and have reviewed the following posts:

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 function:

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)) 

Error:

NOT NULL constraint failed: iapp_rankings.rank

However, the data (minus ranking data) is added to the db.

Any help would be greatly appreciated.


Solution

  • The problem is, that you have fields = ['rank_type']. Try fields = ['rank_type', 'rank'] and it should work.