How to Hydrate dehydrated data and import to DB

Viewed 31

Hi all i tried to export data from django postgresql with django-import-export and was facing issue of resolving the foreign key id to name/title which was resolved by below method and the data was extracted successfully.

class MemberResource(resources.ModelResource):
    Brand=Field()
    class Meta:
        model = model
        fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
        export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
    def dehydrate_Brand(self, obj):
        return str(obj.Brand.title)


class modelAdmin(ImportExportModelAdmin):
    resource_class = MemberResource
    list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories']
    search_fields = ['title','Model_code','Chipset',]
    fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat')
admin.site.register(model,modelAdmin)

now i want to import/upload the data back to database by using the same exported xls without inserting the ID of foreign key and inserting the name of foreign key. need guide to hydrate the data back. i also tried with below hydrate method

def hydrate_Brand(self, obj):
        return str(obj.Brand.title)

def hydrate not showing any error but the data is also not imported to database.

1 Answers

the issue was dehydrating foreign key gives only read-only data which was for the purpose of export only to import we need to use the widgets which will resolve the foreign keys and import the data to database.

Link to Documentation

class MemberResource(resources.ModelResource):
Brand = fields.Field(
column_name='Brand',
attribute='Brand',
widget=ForeignKeyWidget(brand, 'title'))
class Meta:
model = model
fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat')
Related