Hi Robin,
On Thu, 2008-08-28 at 12:55 +0100, Robin Becker wrote:
> My boss, created a model that represents an override to parts of other model
> instances;
Man, I gotta remember to use the "don't shoot me; my boss did it"
reasoning some time. :-)
> the business logic demands that the model instances should be
> uniquely defined by two attributes a and b
>
> ie
>
> o1.a==o2.a and o1.b==o2.b <==> o1 is o2.
>
> I know that we can implement validation rules in the admin to ensure that
> this
> is so, but he prefers to merge an existing instance into the new version at
> save
> time and also delete the existing one. Is that in fact possible with django's
> orm?
>
> I'm thinking of code somewhat like this
>
> def save(self):
>P=list(Over.objects.exclude(id=self.id).
> filter(a=self.a,b=self.b).order_by('id'))
>if P:
> for p in P:
> self.merge(p)
> p.delete()
>super(Over, self).save()
You'll have to write the merge() method yourself, since that's going to
be domain specific (and also doesn't exist in Django). The rest of the
code looks fine, although there are a couple of micro-improvements
possible:
(1) The order_by() call is unnecessary for what you're doing.
(2) If you kept P as a queryset, instead of converting it to a list
(just drop the list() call in the first line), you could write:
for p in P:
self.merge(p)
P.delete()
The delete call is then does as a single SQL statement. As with the
order_by() call, this probably isn't a big deal, since I'd expect P will
either be empty or contain only a very small number of elements. But
wanted to make you aware there is a delete() method on querysets that
does what you would expect.
(3) You can drop the "if P:" test, since everything will work smoothly
if P is empty (the results iterator of the queryset will return nothing
and delete() does nothing on an empty queryset).
Regards,
Malcolm
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
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
-~--~~~~--~~--~--~---