Checking if ManyToManyField is empty in pre_save function

1,037 views
Skip to first unread message

Dagur

unread,
May 1, 2006, 7:08:21 AM5/1/06
to Django users
Hi, I have a ManyToManyField called "authorised" (which is supposed to
be a list of users) and a BooleanField called "is_private" which should
be set to false if there are no users in "authorised" so I did this:

def save(self):
if self.authorised.count() == 0:
self.is_private = False
else:
self.is_private = True
super(Topic, self).save()


But I found out that when creating a new Object and saving it that
is_private is always set to True. On further inspection I found out
that the "authorised" field is set to all users before saving but is
empty after saving.

>>> t = Topic()
>>> t.authorised.count()
2773L
>>> t.save()
>>> t.authorised.count()
0L

Is this the desired behavior?

Luke Plant

unread,
May 1, 2006, 8:53:26 AM5/1/06
to django...@googlegroups.com
On Monday 01 May 2006 12:08, Dagur wrote:

> On further inspection I found out
> that the "authorised" field is set to all users before saving but is
> empty after saving.
>
> >>> t = Topic()
> >>> t.authorised.count()
>
> 2773L
>
> >>> t.save()
> >>> t.authorised.count()
>
> 0L
>
> Is this the desired behavior?

This is kind of a bug, caused by the fact that the ID of 't' is not set
until it is saved, and 'authorised' is a dynamic attribute that does a
database query on the many-to-many database table when you access it.
It's impossible to evaluate .authorised properly until you have saved
the object at least once.

It would be possible to get Django to throw an exception in this case.
What do people think about that?

Luke

--
"In my opinion, we don't devote nearly enough scientific research to
finding a cure for jerks." (Calvin and Hobbes)

Luke Plant || L.Plant.98 (at) cantab.net || http://lukeplant.me.uk/

Ivan Sagalaev

unread,
May 1, 2006, 11:00:58 AM5/1/06
to django...@googlegroups.com
Luke Plant wrote:

>It would be possible to get Django to throw an exception in this case.
>What do people think about that?
>
>

I think it makes sense. As well as documenting that though dependent
objects (both M2M and 12M) look like they are belong to the parent they
really can't be processed in parents save() method because in DB they
are saved separately.

Reply all
Reply to author
Forward
0 new messages