Search code examples
djangotastypie

Tastypie ToOneField not working


My Models:

class UserDetails(models.Model):
    user=models.ForeignKey(User)
    email=models.CharField(max_length=30)
    name=models.CharField(max_length=30)

class Problem(models.Model):
    user=models.OneToOneField(UserDetails)
    onset_time=models.CharField(max_length=20)
    symptoms=models.CharField(max_length=50)

Resources:

class ProblemResource(ModelResource):
    class Meta:
        queryset=Problem.objects.all()
        resource_name="hypo"

class UserResource(ModelResource):
    hypo=fields.ToOneField(ProblemResource,'hypo')
    class Meta:
        queryset=UserDetails.objects.all()
        resource_name="user"

I want to fetch the problem of a particular user using '/user' api call but I am getting this error:-

{"error": "The model '<UserDetails: UserDetails object>' has an empty attribute 'hypo' and doesn't allow a null value."}

I've been through the data and there are no null values .


Solution

  • I was able to solve the problem just by providing related_name='hypo' in Problem model

    class Problem(models.Model):
       user=models.OneToOneField(UserDetails,related_name='hypo')
       onset_time=models.CharField(max_length=20)
       symptoms=models.CharField(max_length=50)
    

    The Django documentation has more details regarding related_name tag.