1

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

2
  • There can be zero, one or multiple such Bs, so how would you "merge" the collection of values of the Bs? Commented Jan 21, 2024 at 22:40
  • What do u mean? the english it's not my main language, please be more specify Commented Jan 21, 2024 at 22:49

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work for me. Send the column name but the data it's empty ¿Do u forgive to use a widget maybe?

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.