title: Run code when "foreign" object is added to set
body: <p>I have a foreign key relationship in my Django (v3) models:</p>
  
  <pre><code>class Example(models.Model):
      title = models.CharField(max_length=200)  # this is irrelevant for the question here
      not_before = models.DateTimeField(auto_now_add=True)
      ...
  
  class ExampleItem(models.Model):
      myParent = models.ForeignKey(Example, on_delete=models.CASCADE)
      execution_date = models.DateTimeField(auto_now_add=True)
      ....
  </code></pre>
  
  <p>Can I have code running/triggered whenever an <code>ExampleItem</code> is "added to the list of items in an <code>Example</code> instance"? What I would like to do is run some checks and, depending on the concrete <code>Example</code> instance possibly alter the <code>ExampleItem</code> before saving it.</p>
  
  <p><strong>To illustrate</strong></p>
  
  <p>Let's say the <code>Example</code>'s class <code>not_before</code> date dictates that the <code>ExampleItem</code>'s <code>execution_date</code> must not be before <code>not_before</code> I would like to check if the "to be saved" <code>ExampleItem</code>'s <code>execution_date</code> violates this condition. If so, I would want to either change the <code>execution_date</code> to make it "valid" or throw an exception (whichever is easier). The same is true for a duplicate <code>execution_date</code> (i.e. if the respective <code>Example</code> already has an <code>ExampleItem</code> with the same <code>execution_date</code>).</p>
  
  <p>So, in a view, I have code like the following:</p>
  
  <pre><code>def doit(request, example_id):
      # get the relevant `Example` object
      example = get_object_or_404(Example, pk=example_id)
      # create a new `ExampleItem`
      itm = ExampleItem()
      # set the item's parent
      itm.myParent = example  # &lt;- this should trigger my validation code!
      itm.save()              # &lt;- (or this???)
  </code></pre>
  
  <p>The thing is, this view is not the only way to create new <code>ExampleItem</code>s; I also have an API for example that can do the same (let alone that a user could potentially "add <code>ExampleItems</code> manually via REPL). Preferably the validation code must not be duplicated in all the places where new <code>ExampleItems</code> can be created.</p>
  
  <p>I was looking into <code>Signals</code> (<a href="https://docs.djangoproject.com/en/3.0/topics/signals/" rel="nofollow noreferrer">Django docu</a>), specifically <code>pre_save</code> and <code>post_save</code> (of <code>ExampleItem</code>) but I think <code>pre_save</code> is too early while <code>post_save</code> is too late... Also <code>m2m_changed</code> looks interesting, but I do not have a many-to-many relationship.</p>
  
  <p>What would be the best/correct way to handle these requirements? They seem to be rather common, I imagine. Do I have to restructure my model?</p>