Я хочу добавить несколько брендов в магазин из представления администратора родительской модели, но постоянно получаю сообщение об ошибке:
Line number: 4 - get() returned more than one Brands -- it returned 2!
models.py
class Store(models.Model):
store = models.IntegerField(primary_key=True)
state = models.CharField(max_length=250, blank=True)
# pylint: disable=R0903
def __str__(self):
return '{}'.format(self.store)
class Brand(models.Model):
store = models.ForeignKey('Store', on_delete=models.CASCADE, blank=True, null=True)
company = models.CharField(max_length=250, blank=True)
# top selling rank
rank = models.IntegerField(blank=True, default='')
# pylint: disable=R0903
def __str__(self):
return '{}'.format(self.store)
admin.py
class StoreInline(admin.StackedInline):
model = Brand
class StoreResource(resources.ModelResource):
store = fields.Field(attribute='store', column_name='Store')
state = fields.Field(attribute='state', column_name='State')
company = fields.Field(attribute='company', column_name='Company', widget=ForeignKeyWidget(Brand, 'company'))
rank = fields.Field(attribute='rank', column_name='Rank', widget=ForeignKeyWidget(Brand, 'rank'))
class Meta:
model = Store
import_id_fields = ('store', 'state',)
fields = ('store', 'state', 'company', 'rank')
def before_import_row(self, row, **kwargs):
company = row.get('Company')
rank = row.get('Rank')
company = Brand.objects.get_or_create(company=company, rank=rank)
class StoreAdmin(ImportExportModelAdmin):
inlines = [BrandInline]
resource_class = StoreResource
list_display = ['store', 'state']
class Meta:
model = Store
admin.site.register(Store, StoreAdmin)
Но когда я загружаю CSV через дочернюю модель, он добавляет данные без проблем. код для этого ниже. По причинам читабельности id лучше загрузить его через родителя. код для детского админа ниже
class StoreResource(resources.ModelResource):
store = fields.Field(attribute='store', column_name='Store', widget=ForeignKeyWidget(Store, 'store'))
state = fields.Field(attribute='state', column_name='State', widget=ForeignKeyWidget(Brand, 'state'))
company = fields.Field(attribute='company', column_name='Company')
rank = fields.Field(attribute='rank', column_name='Rank')
class Meta:
model = Brand
import_id_fields = ('company',)
fields = ('store', 'company', 'rank')
def before_import_row(self, row, **kwargs):
store = row.get('Store')
state = row.get('State')
store = Store.objects.get_or_create(store=store, state=state)
class BrandAdmin(ImportExportModelAdmin):
resource_class = BrandResource
list_display = ('store',)
class Meta:
model = Brand
admin.site.register(Brand, BrandAdmin)