[Django]-Why doesn't django automatically update the foreign key? (obj.relative.id != obj.relative_id)

3👍

When you generate an order by self.order = Order(), the id is not set as it is when you call the order’s save method. So your order_id field for your Peon object is set to None.

If all of your order’s field are optional you can do something like self.order = Order.objects.create() and then the id will be set correctly.

Otherwise you will need to do something like

def save(self, *args, **kwargs):
  if self.order_id is None:
    order = Order()
    #edit self.order's fields appropriately
    order.generate(...)
    self.order = order

  else:
    #edit self.order's fields appropriately
    self.order.generate(...)

  self.order.save()

  super(Peon, self).save(*args, **kwargs)

If order.generate doesn’t need the backward relation of course.

Leave a comment