Z
Z
zagogulka2022-01-16 14:27:19
Python
zagogulka, 2022-01-16 14:27:19

How to automatically create a record in one table when creating a record in another (Django models)?

Good afternoon, I have two tables in the database
First:

class Zakaz(models.Model):
    sl_date = models.DateTimeField('Дата создания заказа')
    sl_no = models.CharField(max_length=20, verbose_name='Название заказа')
    sl_zak = models.CharField(max_length=20, verbose_name='Номер заказа')
    sl_kol = models.IntegerField(verbose_name='Количество изделий в заказе')

    def __str__(self):
        return '%s - %s' % (self.sl_no, self.sl_zak)

    class Meta:
        verbose_name_plural = 'Заказы'


Second:
class ZakazSnab(models.Model):
    sn_date = models.DateTimeField('Дата создания заказа')
    sn_zak = models.CharField(max_length=20, verbose_name='Название заказа')
    sn_no = models.CharField(max_length=20, verbose_name='Номер заказа')
    sn_kol = models.IntegerField(verbose_name='Количество изделий в заказе')
    sn_manager = models.CharField(max_length=20, verbose_name='Ответственный менеджер', blank=True, null=True)

    def __str__(self):
        return '%s - %s' % (self.sn_no, self.sn_date)

    class Meta:
        verbose_name_plural = 'Снабженец, закрепленный за заказом'


The question is: how to automatically create a ZakazSnab object when creating a Zakaz object, with the corresponding fields from Zakaz filled in (Order date, order number, quantity, etc.)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2022-01-16
@zagogulka

from django.db.models.signals import post_save
from django.dispatch import receiver


# method for updating
@receiver(post_save, sender=Zakaz)
def update_stock(sender, instance, **kwargs):
    # instance - созданный объект, к которому можно обратится 
    # Здесь создавать объект

UPD: in the first comment - a detailed example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question