On 12 Jun 2012, at 10:44, Gelonida N wrote:

> On 06/12/2012 05:44 AM, Jerome Baum wrote:
>> Drop the "defaults" kwarg to get_or_create as apparently you're not
>> using it. Also drop the conditional on those set/save statements.
>> 
>> 
> 
> Wouldn't this create more db accesses than the original code?

get_or_create causes one or two accesses (depending), and the save() call 
causes another (I think). Two scenarios:

1. Object existed already. Original code: get_or_create causes one access, 
save() another, for a total of two. New code: ditto.

2. Object didn't exist. Original code: get_or_create causes two access, no 
save() call, for a total of two. New code: get_or_create causes two accesses, 
save() another, for a total of three.

So yes one more call if the object didn't exist. But DRY.

Alternatively create a utility method to handle this. Example ("pseudo-code"):

def get_or_create_ensuring(qs=None, filters={}, ensure={}):
    """
    get_or_create with defaults. If the object existed then change it.
    """
    obj, created = qs.get_or_create(**filters, defaults=ensure)
    if not created:
        obj.__dict__.update(ensure)
        obj.save()

You can also create a new query manager, though it won't work on all models. 
Alternatively a wrapping query manager (i.e. __init__ it based on an existing 
one).


.-.-.

-- 
No situation is so dire that panic cannot make it worse.
--
Please encrypt sensitive information before emailing it:
https://jeromebaum.com/pgp/encrypt.html
--
PGP: 2C23 EBFF DF1A 840D 2351 F5F5 F25B A03F 2152 36DA

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" 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-users?hl=en.

Reply via email to