Search code examples
djangotastypie

Tastypie following a reverse relationship - not working to use related_name


I have two models.

Parent

class Parent(models.Model):
    ... code

Child

class Child(models.Model):
    ... code
    parent = models.ForeignKey(Parent, related_name="parents")

And an API

class ParentResource(ModelResource):
    children = fields.ToManyField("project.module.api.ChildResource", 'children', related_name='parents', null=True, blank=True, full=True)

    class Meta:
        queryset = Parent.objects.all()

and

class ChildResource(ModelResource):
    parent = fields.ForeignKey("project.module.api.ParentResource", 'parent')

    class Meta:
        queryset = Child.objects.all()

When I try to visit the parent resource, the array for children is empty. Any help clarifying would be welcome.

I've looked at previous answers here and here and the docs here but I'm still not able to see what is going on.

Thanks


Solution

  • From your code:

        parent = models.ForeignKey(Parent, related_name="parents")
    

    related_name sets the attribute name on the Parent model (also does the same on tastypie resources), with the default being child_set and you're now setting it to parents. That means a Parent model p would have a queryset of Child objects at the attribute named parents, which is obviously not right.

    Additionally, the related_name on ChildResource for the parent relationship doesn't match the attribute on the related model.

    Below are corrected versions of each that should just work:

    Models

    class Parent(models.Model):
        ... code
    
    class Child(models.Model):
        ... code
        parent = models.ForeignKey(Parent, related_name="children")
    

    Resources

    class ParentResource(ModelResource):
        children = fields.ToManyField("project.module.api.ChildResource", 'children', related_name='parent', null=True, blank=True, full=True)
    
        class Meta:
            queryset = Parent.objects.all()
    
    class ChildResource(ModelResource):
        parent = fields.ForeignKey("project.module.api.ParentResource", 'parent')
    
        class Meta:
            queryset = Child.objects.all()