Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

502
Vistas
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!

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Your Declaration of

form.save_m2m()

should be after

obj.save()

After saving of object Many to Many field will add

about 4 years ago · Santiago Trujillo Denunciar

0

Your models are bellow:

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 you want to create a Article instance with tags, you should create the instance firstly, then add the tags, like bellow:

article = Article.objects.create()

tags = [tag_instance1, tag_instance2, tag_instance3 ...]

article.tags.set(tags)

or

article.tags.add(tag_instance)
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda