#13777: problems using **kwargs to create an instance of a model with an
AutoField
primary key
------------------------------------------+---------------------------------
Reporter: seth_a | Owner: nobody
Status: new | Milestone:
Component: Database layer (models, ORM) | Version: 1.2
Keywords: **kwargs, AutoField | Stage: Unreviewed
Has_patch: 1 |
------------------------------------------+---------------------------------
I've found that if you create a simple model with an AutoField for a
primary key, even the default one, like:
{{{
from django import models
class simple(models.Model):
data = models.CharField()
}}}
creating and saving an instance with:
{{{
temp = simple(data="example")
temp.save()
}}}
causes no problems. If you use **kwargs, however:
{{{
temp = simple(**{'data':'example'})
temp.save()
}}}
then django never defines the Autofield, so when _get_pk_val is called in
django/trunk/django/db/models/base.py, its getattr call never finds the
field id (or whatever you named it, I tested with explicitly defining an
AutoField named blah).
The solution to this is to change _get_pk_val from:
{{{
def _get_pk_val(self, meta=None):
if not meta:
meta = self._meta
return getattr(self, meta.pk.attname)
}}}
to:
{{{
def _get_pk_val(self, meta=None):
if not meta:
meta = self._meta
try:
return getattr(self, meta.pk.attname)
except AttributeError:
return None
}}}
As None was what this function was supposed to return when the primary key
did not exist, the rest of the calling function can now do the right thing
and create the AutoField, which I've tested and few times with both the
default AutoField and an explicitly defined AutoField primary key, and
things seem to work.
There may have been a way to handle this earlier in the code when **kwargs
was checked, but this was the easiest fix.
And sorry for not having an svn diff! I don't have the development code
checked out, and this is my first patch submission.
Also, I've noticed that the code looks the same in the dev version.
Perhaps it has the same problem.
--
Ticket URL: <http://code.djangoproject.com/ticket/13777>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-updates?hl=en.