Exporting data of non-related with the model

58 Views Asked by At

I'm using Django-import-export on django admin. I want to export the data that are not related. (Are related but it's weird..) Example:

models.py

class A(models.Model):
    name = models.CharField(default=False)
    size= models.CharField(default=True)

class B(models.Model):
    relation = models.ForeignKey(A,on_delete=models.CASCADE)
    title = models.CharField(default=False)
    category = models.CharField(default=False)

I want something like this:

admin.py
class export(resources.ModelResource):
   name = Field(column_name='something',attribute='name')
   category =Field(column_name='something_else',attribute='category')

   class Meta:
       model = A
       fields = ('name','category')
class A_Admin(ExportActionMixin,admin.ModelAdmin):
    resource_class=export
    ....
    ....

I need to get the data from model B that have a relation with A but A dont have relation with B...

1

There are 1 best solutions below

1
Tusher On

To export data from model B that has a relation with A, but where A does not have a direct relation with B, you can use the

ForeignKey__isnull

field in your export class. This will filter out the instances of A that do not have a related instance in B.

from import_export import resources, fields
from import_export.admin import ExportActionMixin
from .models import A, B

class ExportResource(resources.ModelResource):
    name = fields.Field(column_name='something', attribute='name')
    category = fields.Field(column_name='something_else', attribute='b__category')

    class Meta:
        model = A
        fields = ('name', 'category')

class A_Admin(ExportActionMixin, admin.ModelAdmin):
    resource_class = ExportResource
    list_display = ('name', 'size')  # Add any other fields you want to display in the admin

    def get_queryset(self, request):
        # This queryset filters out instances of A that do not have a related instance in B
        return super().get_queryset(request).exclude(b__isnull=True)

admin.site.register(A, A_Admin)