A
A
artem_sib2020-02-19 23:44:46
Django
artem_sib, 2020-02-19 23:44:46

How to add an entry to a model when changing or saving another model?

Tell me, I want to implement something like alloying, when adding information in one model, it is necessary to make changes to another model, I read about the save, pre_save methods, but in all examples it is only considered what to do with the current model before saving, I will be grateful for a small example

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-02-20
@artem_sib

If I understand correctly, you require a signal without specifying sender, which will fire when any model is saved:

@receiver(pre_save)
def event_to_history_annals(sender, instance, **kwargs):
    try:
        Event.objects.create(
            instance=f'{instance._meta.app_label}.{instance._meta.object_name}.{instance.pk}',
            # Всякие другие поля
        )
    except Exception as e:
        logger.exception('Что-то пошло не так...')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question