djangodjango-import-export

Why field change in djnago import export doesn't work?


I need to import ManyToMany relationships not by the id field, but by the number(from class Part) field. I know that this is done using through_fields, but I do not fully understand how to do it

I need to determine by number field instead of id \

1

models.py

class Part(models.Model):
    brand = models.CharField('Производитель', max_length=100, blank=True)
    number = models.CharField('Артикул', max_length=100, unique=True)
    name = models.CharField('Название', max_length=100, blank=True)
    description = models.TextField('Комментарий', blank=True, max_length=5000)
    analog = models.ManyToManyField('self', through='ContactConnection',blank=True, related_name='AnalogParts')
    images = models.FileField('Главное изображение', upload_to = 'parts/', blank=True)
    images0 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True)
    images1 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True)
    images2 = models.FileField('Дополнительное фото', upload_to = 'parts/', blank=True)

    def __str__(self):
        return str(self.number)
        return self.name

    class Meta:
        verbose_name = 'Запчасть'
        verbose_name_plural = 'Запчасти'

class PartConnection(models.Model):
    to_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='to_parts')
    from_part = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='from_parts')

Solution

  • This is easily done specifying the primary_key=True option in the field itself. You'll likely want to define it like this;

    number = models.CharField('Артикул', max_length=100, unique=True, primary_key=True)
    

    This will now grant you access to the number with instance.pk If you want it to be called id, you just add it like this;

    id = models.CharField('Артикул', max_length=100, unique=True, primary_key=True)