I have created a function that will add objects to a model. It looks like this:
def add_objects(self,obj_name_list):
for obj in obj_name_list:
o = Obj.objects.create(name=obj)
self.objs.add(o)
self.save(update_fields['objs'])
But when I am running it I get the following error:
ValueError: The following fields do not exist in this model or are m2m fields: objs
the error is coming from the save()
call, but I don't understand why...in your answer please give a detailed explanation. Thanks!
Here is the traceback
.../models.pyc in add_objects(self, obj_name_list)
125 o = Obj.objects.create(name=obj) #create the tag
126 self.objs.add(o) #add the new tag to the foreign key
--> 127 self.save(update_fields=['objs'])
128 except TypeError:
129 raise TypeError("You can only add objects as a string or list")
.../models.pyc in save(self, *args, **kwargs)
95 if not self.pk:
96 is_created = True
---> 97 super(Model, self).save(*args, **kwargs)
98 if is_created:
99 signals.model_created.send(sender=self.__class__) #send signal if just created
/Library/Python/2.7/site-packages/Django-1.6-py2.7.egg/django/db/models/base.pyc in save(self, force_insert, force_update, using, update_fields)
523 raise ValueError("The following fields do not exist in this "
524 "model or are m2m fields: %s"
--> 525 % ', '.join(non_model_fields))
526
527 # If saving to the same database, and this model is deferred, then
A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.
Django will automatically generate a table to manage many-to-many relationships. You might need a custom “through” model. The most common use for this option is when you want to associate extra data with a many-to-many relationship.
A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.
As the traceback shows, that isn't the code you were running. The problematic code is this:
self.save(update_fields=['objs'])
which does cause a problem, because objs
is not an actual field on that model: it's a column in a linking table.
In fact, if you haven't modified any other fields, there's no need to call save at all: calling add on the m2m field already modifies the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With