Sunday, June 8, 2014

Why doesn't saving a related model update the _id field?

I'm confused by Django's behaviour when saving related models. Take for example:

class X(models.Model):
    pass

class Y(models.Model):
   x = models.ForeignKey(X)

Now if I create some objects (unsaved):

x = X()
y = Y(x=x)

All well so far. But now odd things happen when I save:

A) y.save() throws an integrity error because there's no PK for x

I kind of understand this, but it's not obvious to me why Django doesn't at least try to save the related object first

B) y.x.save(); y.save() also throws an integrity error because y.x_id is None. 

However, y.x.id is not None, so I don't understand why it can't update y.x_id (and thus make the save succeed).

C) y.x.save(); y.x = y.x; y.save() - succeeds, but I don't see why the y.x = y.x is needed.

Is this a deliberate design decision, something I'm misunderstanding, or a bug/implementation artefact?

I'm running into this with serialization in Django Rest Framework - my API provides a facade over something that's actually stored across two models, so when creating the resource I want to deserialise the data into the two related models. DRF serializers by default return unsaved versions of the model, but this is broken by the above.

Any insight into what's going on and why would be much appreciated.

Cheers,

Malcolm


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/21f29ffc-29ba-40f3-9143-25fed227d4af%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment