ManyToManyField is empty in post_save() function

前端 未结 1 886
暖寄归人
暖寄归人 2021-02-09 03:26

When a new record is added to a table, I have to execute a SQL statement on an external database. This query includes the use of a ManyToManyField. So I just connected the funct

1条回答
  •  被撕碎了的回忆
    2021-02-09 03:27

    This is because you first save your instance and after that you add m2m relations to it. This is how ManyToMany fields work in Django data models. Django needs to know the ID of the items that should be connected with m2m relations.

    I think that your code looks like this:

    instance = MyModel.objects.create(some_field=some_value)  # post save signal triggered here
    instance.my_m2mfield = my_set_of_m2m_models
    

    You need to connect your handler to the django.db.models.signals.m2m_changed signal. See the docs. For example:

    def post_save_mymodel(sender, instance, action, reverse, *args, **kwargs):
        if action == 'post_add' and not reverse:
            for e in instance.my_m2mfield.all():
                # Query including "e"
    m2m_changed.connect(post_save_mymodel, sender=MyModel.my_m2mfield.through)
    

    0 讨论(0)
提交回复
热议问题