0

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

2
  • It looks fine as you have it and it should work and export 'name'. Set a breakpoint in ForeignKeyWidget.render() and see what field is being read. Commented Jun 4, 2024 at 9:55
  • additionally, please use v4 and declare resources_classes = [reportResource] Commented Jun 4, 2024 at 14:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.