Search code examples
djangodjango-import-export

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


I have it almost working.

Models:

class Child(models.Model):
    parent = models.ForeignKey('project.Parent')
    name = models.CharField(max_length=100)

class Parent(models.Model):
    text = models.CharField(max_length=100)

Resource:

class ParentResource(resources.ModelResource):
    children = fields.Field(widget=widgets.ForeignKeyWidget(Parent))

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

Then the view calls the resource and downloads it. The issue is, name is blank. So, everything else works just fine, but I can't get child.name to show up. What am I missing?


Solution

  • 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.