views:

30

answers:

2

I have a django model (A) which has a ManyToManyField (types) to another model (B). Conceptually the field in A is an 'optionally limit this object to these values'. I have set blank=null and null=True on the ManyToManyField. I have created an object from this model, and set types to some values. All is good.

I want to set it to 'null', i.e. disable it. But in the django shell, I get the following errors:

>>> o.types.all()
[<Type: foo>, <Type: bar>]
>>> o.types = None
File "<console>", line 1, in <module>
File ".../virtualenv/lib/python2.6/site-packages/django/db/models/fields/related.py", line 627, in __set__
manager.add(*value)
TypeError: add() argument after * must be a sequence, not NoneType

I can successfully set it to [] (the empty list), but I would like to set it to None, since I want to use None as a signal/flag. Is this possible in Django models?

I'm using Django 1.1

+2  A: 

That's what clear() is for.

http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear

Perhaps you're looking for remove()?

http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove

S.Lott
clear() looks like a good start. After doing clear(), is the field set to [] or None?
Rory
@Rory: When you tried it, what did you observe?
S.Lott
+1  A: 

I don't think it is possible to set it to None - think about how M2M is implemented on the SQL layer (it is an intermidiate table, where can you write your "None" to?).

If you need a separate flag, why not introduce another column?

cheshire