Django - Where should signals be placed?

Viewed 45

collection.models.py:

class Collection(Model):
  items = ManyToManyField(Item)
  ...

item.models.py

class Item(Model):
  state = OneToOneField('ItemState')
  ...

class ItemState(Model):
  item = ForeignKey('Item')
  ...

Structure explanation: An item only has a single state at a time, but the client wants to track its state history.

I want to write a signal that creates a new state when a Collection is created. Due to circular imports, I am separating my signals from my models. Now my question is do I write the signal for the above mentioned under collection_signals.py or item_state_signals.py.

My guess is that both will work, but what would be the logical place to search for the above mentioned signal? I assumed collection since Collection is the sender, but then again this is about creating states and various models will be creating states (e.g. when a new item gets created that should trigger a new state as well)

1 Answers

I presume collection and item are your two Django Apps. So, create a module inside the app named signals.py. So, there will be two files (ideally)

  1. collection/signals.py
  2. item/signals.py

I want to write a signal that creates a new state when a Collection is created.

So, here the sender will be the Collection and conventionally, the corresponding signal will be in collection/signals.py.

In short, look at your sender class, check where it belongs and create the signal inside the app.

Related