I have a model represents some item on stock:
(Code has been simplified)
class StockItem(models.Model):
name = models.CharField()
category = models.Charfield()
stock = models.ForeignKey(Stock) # <- Here is few stocks
quantity = models.IntegerField(default=0)
So every StockItem may exist on different stocks but with different q-ty remained. Is there a way to create ModelResource to export quantity remained for every stock?
Table example:
+----+--------+----------+---------+---------+
| ID | Name | Category | Stock A | Stock B |
+----+--------+----------+---------+---------+
| 1 | Item 1 | Cat 1 | 1 | 1 |
| 2 | Item 2 | Cat 2 | 10 | 8 |
| 3 | Item 3 | Cat 3 | 14 | 32 |
+----+--------+----------+---------+---------+
My ModelResource:
class StockItemsRemainingsResource(resources.ModelResource):
class Meta:
model = models.StockItem
fields = ('name', 'category')
def __init__(self):
super().__init__()
for item in self.get_queryset():
stock_name = item.stock.name
self.fields[f"quantity_{stock_name}"] = fields.Field(
attribute="quantity",
column_name=stock_name,
widget=widgets.ForeignKeyWidget(
models.Stock,
"pk"
)
)
I was trying to override the __init__ method but probably did it wrong.