Search code examples
djangodjango-import-export

Import using 2 fields as id field


I have read the documentation for django import_export and noticed that we can import with import_id_fields which field to use as the import id. I was wondering if it is possible to use the combination of fields.

For example, I have a model choice field month and name, so during the import, it takes two fields and uses as import id?

P.S I apologize for my broken English (it is my 3rd language)

models.py:

class Book(models.Model):
    JANUARY = '1'
    FEBRUARY = '2'
    MARCH = '3'
    APRIL = '4'
    MAY = '5'
    JUNE = '6'
    JULY = '7'
    AUGUST = '8'
    SEPTEMBER = '9'
    OCTOBER = '10'
    NOVEMBER = '11'
    DECEMBER = '12'

    MONTH_CHOICES = (
        (JANUARY, 'January'),
        (FEBRUARY, 'February'),
        (MARCH, 'March'),
        (APRIL, 'April'),
        (MAY, 'May'),
        (JUNE, 'June'),
        (JULY, 'July'),
        (AUGUST, 'August'),
        (SEPTEMBER, 'September'),
        (OCTOBER, 'October'),
        (NOVEMBER, 'November'),
        (DECEMBER, 'December'),
    )

    name = models.CharField('Book name', max_length=100)
    author = models.ForeignKey(Author, models.SET_NULL, blank=True, null=True)
    author_email = models.EmailField('Author email', max_length=75, blank=True)
    imported = models.BooleanField(default=False)
    published = models.DateField('Published', blank=True, null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    categories = models.ManyToManyField(Category, blank=True)
    month = models.CharField(
        max_length=2,
        choices= MONTH_CHOICES,
        default=JANUARY,
    )


    def __str__(self):
        return self.name

admin.py: 


# Register your models here.
class BookResource(resources.ModelResource):

    class Meta:
        model = Book
        import_id_fields = ('name',)
        fields = ('name', 'price','month')



@admin.register(Book)
class BookAdmin(ImportExportActionModelAdmin):
    resource_class = BookResource

Solution

  • Yes it looks like you can. I believe your resource model should looke like this:

    class BookResource(resources.ModelResource):
        class Meta:
            model = Book
            import_id_fields = ('name', 'month')
            fields = ('name', 'price','month')