Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - ManyToManyField in a model, setting it to null?

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

like image 795
Amandasaurus Avatar asked Oct 12 '10 10:10

Amandasaurus


1 Answers

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

like image 139
S.Lott Avatar answered Nov 14 '22 21:11

S.Lott