Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Many to Many field causing an error

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
like image 959
Ryan Saxe Avatar asked Jan 16 '14 19:01

Ryan Saxe


People also ask

How does many-to-many field work in Django?

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.

How does Django handle many-to-many relationship?

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.

How take data from many-to-many field in Django?

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.


1 Answers

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.

like image 84
Daniel Roseman Avatar answered Oct 19 '22 19:10

Daniel Roseman