Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object needs to have a value for field "id" before this many-to-many relationship can be used in Django

I have the following code in my models.py:

class Tag(models.Model):
    name = models.CharField(max_length=75)

class Article(models.Model):
    tags = models.ManyToManyField(Tag)

    def save(self, *args, **kwargs):
        for tag in self.tags:
            print tag.name
        super(Article, self).save(*args, **kwargs)

When I try to create an article from the admin panel, I get the following error:

ValueError: "<Article>" needs to have a value for field "id" before this many-to-many relationship can be used.

How can I fix this problem? I need to access and iterate the tags before saving the article. Thanks!

like image 429
darkhorse Avatar asked May 02 '17 17:05

darkhorse


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 do I create a many-to-many relationship in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.

How fetch 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.

What is through in Django models?

The through attribute/field is the way you customize the intermediary table, the one that Django creates itself, that one is what the through field is changing.


1 Answers

Your Declaration of

form.save_m2m()

should be after

obj.save()

After saving of object Many to Many field will add

like image 157
Aditya R Avatar answered Oct 11 '22 07:10

Aditya R