The right place to keep my signals.py file in a Django project

前端 未结 8 961
天涯浪人
天涯浪人 2020-11-27 14:24

Based on Django\'s documentation I was reading, it seems like signals.py in the app folder is a good place to start with, but the problem I\'m facing is that wh

8条回答
  •  情话喂你
    2020-11-27 14:29

    An alternative is to import the callback functions from signals.py and connect them in models.py:

    signals.py

    def pre_save_callback_function(sender, instance, **kwargs):
        # Do stuff here
    

    model.py

    # Your imports here
    from django.db.models.signals import pre_save
    from yourapp.signals import pre_save_callback_function
    
    class YourModel:
        # Model stuff here
    pre_save.connect(pre_save_callback_function, sender=YourModel)
    

    Ps: Importing YourModel in signals.py will create a recursion; use sender, instead.

    Ps2: Saving the instance again in the callback function will create a recursion. You can make a control argument in .save method to control it.

提交回复
热议问题