В Django обновление другой таблицы во время сохранения записи из одной таблицы
Мои таблицы:
models.py
class Warehouse(models.Model): site_name = models.CharField(max_length=100)
class Item(models.Model): item = models.CharField(max_length=100)
class WarehouseStockStatus(models.Model):
название_сайта = models.ForeignKey(Warehouse, on_delete=models.CASCADE)
item = models.ForeignKey(Item,on_delete=models.CASCADE,editable = False)
class Meta:
unique_together = (("site_name", "item"))
stock_opening_quantity = models.PositiveBigIntegerField(
default = 0,
editable = False
)
stock_consumption_quantity = models.PositiveBigIntegerField(
default = 0,
editable = False
)
current_inventory_level = models.PositiveBigIntegerField(
default = 0,
editable = False
)
class InventoryOpenings(models.Model):
название_сайта = models.ForeignKey(Warehouse, on_delete=models.CASCADE,related_name='openings')
transaction_number = models.BigAutoField(primary_key = True,
serialize = False)
class InventoryOpeningsDetails(models.Model):
transaction_number = models.ForeignKey(InventoryOpenings, on_delete=models.CASCADE)
item = models.ForeignKey(Item,on_delete=models.CASCADE)
opening_quantity = models.PositiveBigIntegerField(
default = 0,
editable = True
)
Имеется одна таблица Warehouse, содержащая от одной до многих записей в WarehouseStockStatus. Есть одна таблица Products или Items для управления запасами. Затем есть таблица InventoryOpenings и InventoryOpeningsDetails, где мы выбираем склад, а затем товар, добавляем поле opening_quantity.
Я хочу обновить WarehouseStockStatus для этой комбинации склада и товара, обновляя поля stock_opening_quantity и current_inventory_level в этой таблице со значением открытия, которое мы вводим для InventoryOpeningsDetails.
Я пытаюсь разместить код для этого в admin.py, в InventoryOpeningsAdmin. Нужна помощь.
Попробовал этот код в админке
класс InventoryOpeningsAdmin(admin.ModelAdmin):
def after_saving_model_and_related_inlines(self, obj):
mysite = InventoryOpenings.objects.values_list('site_name',flat=True)[0]
myitem = InventoryOpeningsDetails.objects.values_list('item', flat=True)[0]
try:
warehouse_item = WarehouseStockStatus.objects.filter(Q(site_name=mysite, item=myitem)).select_related(Warehouse) #.update_or_create(site_name=mysite, item=myitem)
except WarehouseStockStatus.DoesNotExist:
WarehouseStockStatus.objects.create(site_name=mysite, item=myitem)
warehouse_item = WarehouseStockStatus.objects.filter(Q(site_name=mysite, item=myitem)).select_related(Warehouse)
stock_op_qty = WarehouseStockStatus.stock_opening_quantity
stock_cur_qty = WarehouseStockStatus.current_inventory_level
op_qty = InventoryOpeningsDetails.opening_quantity
updated_op_qty = stock_op_qty + op_qty
updated_cur_qty = stock_cur_qty + op_qty
warehouse_item.stock_opening_quantity = updated_op_qty
warehouse_item.current_inventory_level = updated_cur_qty
for allitems in warehouse_item:
warehouse_item.save()
Что-то вроде этого?, проверьте сигналы Django
from django.dispatch import receiver
from django.db.models.signals import post_save,pre_save
class Warehouse(models.Model):
site_name = models.CharField(max_length=100)
class Item(models.Model):
item = models.CharField(max_length=100)
class Meta:
unique_together = (("site_name", "item"))
stock_opening_quantity = models.PositiveBigIntegerField(default = 0,editable = False)
stock_consumption_quantity = models.PositiveBigIntegerField(default = 0,editable = False)
current_inventory_level = models.PositiveBigIntegerField(default = 0,editable = False)
class WarehouseStockStatus(models.Model):
site_name = models.ForeignKey(Warehouse, on_delete=models.CASCADE)
item = models.ForeignKey(Item,on_delete=models.CASCADE,editable = False)
class InventoryOpenings(models.Model):
site_name = models.ForeignKey(Warehouse, on_delete=models.CASCADE,related_name='openings')
transaction_number = models.BigAutoField(primary_key = True, serialize = False)
class InventoryOpeningsDetails(models.Model):
transaction_number = models.ForeignKey(InventoryOpenings, on_delete=models.CASCADE)
item = models.ForeignKey(Item,on_delete=models.CASCADE)
opening_quantity = models.PositiveBigIntegerField(default = 0,editable = True)
@receiver(post_save,sender=InventoryOpenings)
def update_item(sender,instance,*args,**kwargs):
item = instance.item
item.stock_opening_quantity = instance.opening_quantity
item.current_inventory_level = item.current_inventory_level + instance.opening_quantity
item.save()