[Answer]-Tastypie following a reverse relationship – not working to use related_name

1👍

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

Leave a comment