On Thu, Mar 25, 2010 at 5:52 AM, Kenneth Gonsalves <law...@au-kbc.org> wrote:
> hi,
>
> I have a model like this:
>
> name - unique
> slno - not null
> mode - not null
>
> If the instance does not exist and I give all three values to get_or_create,
> it works
>
> if the instance exists, and I give values for slno and mode which are 
> different
> from the existing ones - I get a programming error as get_or_create tries to
> create a new instance and falls foul of the unique constraint on name. It
> works if I only give the value for name - it gets the instance and then I can
> add the new values and save
>
> if the instance does not exist and I only give the value for name, I get a
> programming error that the not null constraints on slno and mode are violated.
>
> so it looks to me that get_or_create will only work reliably when there are no
> not null or unique constraints in the model. Or am I missing something?

I think you are missing the optional kwarg 'initial', which is a
dictionary of initial values to use when the instance does not exist.
So not

foo, created = Foo.objects.get_or_create(name=name,
                                         sino=sino,mode=mode)

but

foo, created = Foo.objects.get_or_create(name=name,
                                initial={'sino': sino, 'mode': mode, })

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to