[Answered ]-Getting a field value from a field via a ForeignKey widget in reverse with django-import-export

2👍

First of all, widgets.ForeignKeyWidget is used by modelA to look up a related modelB that is a ForeignKey of modelA.

I.e. a ChildResource can use widgets.ForeignKeyWidget to look up a Parent, but not vice versa.

Doing it in reverse, i.e. to loop up and/or display some fields of a set of Childs (who has a ForeignKey Parent) from a ParentResource, you need to do something like this:

from import_export import fields, resources
from .models import Parent


class ParentResource(resources.ModelResource):

    children = fields.Field()

    class Meta:
        model = Parent
        use_transactions = True
        fields = ('text', 'children')

    def dehydrate_children(self, parent):
        children = list(parent.child_set.all())
        return ','.join([child.name for child in children])

Using the dehydrate() method. Then when you export ParentResource, you’ll get a dataset object with a "children" key whose value is a comma-separated list of the names of its children.

Leave a comment