I seem to be having some issues trying to figure out how to use the ForeignKeyWidget in the django-import-export package. I’m hoping someone here will be able to point out what is wrong with my code. I’m able to export the data I want except for the asset. I would like it to be the name of the asset, but it is exporting the ID.
Here is my models
from django.db import models
from datetime import datetime
class asset(models.Model):
name = models.CharField(max_length=8)
def __str__(self):
return f"{self.id} {self.name}"
class report(models.Model):
machine = models.ForeignKey(asset, on_delete=models.CASCADE)
last_active = models.DateField()
return_code = models.CharField(max_length=16, blank=True)
comment = models.CharField(max_length=256, blank=True)
status = models.CharField(max_length=256, blank=True)
@property
def since(self):
return (datetime.now().date() - self.last_active).days
def __str__(self):
return f"{self.machine} {self.last_active} {self.return_code} {self.comment} {self.status}"
Here is my admin.py
from django.contrib import admin
from django.contrib.admin import DateFieldListFilter
from import_export.admin import ImportExportModelAdmin
from import_export import fields, resources
from import_export.widgets import ForeignKeyWidget
from .models import asset, report
class reportResource(resources.ModelResource):
machine = fields.Field(
column_name='machine',
attribute='machine',
widget=ForeignKeyWidget(asset, 'name'))
class Meta:
model = report
# fields = ('machine',)
class reportAdmin(ImportExportModelAdmin, admin.ModelAdmin):
list_display = ("machine", "last_active", "return_code", "comment", "status")
resources_class = reportResource
admin.site.register(report, reportAdmin)
admin.site.register(asset)
I’m exporting the report data. I would like to have the name of the asset instead of the ID.
I tried following the example provided in the document https://django-import-export.readthedocs.io/en/latest/api_widgets.html#import_export.widgets.ForeignKeyWidget
But it is still exporting the asset ID instead of the name