2

I have a system with several steps. Each step increments one single object instance. I want to save the instance in db only in the final step, on others just update the instance I saved in the session.

My model class seems like this:

class Proposta(models.Model):
    Modelo = models.ForeignKey("ModeloVersao", verbose_name="Modelo")
    Pacotes = models.ManyToManyField("PacoteModelo", null=True, blank=True)
    Opcionais = models.ManyToManyField("ItemModelo", null=True, blank=True)
    RevestimentoInterno = models.ForeignKey("RevestimentoInternoModelo", verbose_name="Revestimento Interno")
    Cor = models.ForeignKey("CorModelo")
    CorSecundaria = models.ForeignKey("CorModeloSecundaria", verbose_name="Cor secundária", null=True, blank=True)
    Data = models.DateTimeField(auto_now_add = True)
    Status = models.CharField("Status", choices=STATUS_PROPOSTA, max_length=10)
    Cliente = models.ForeignKey("Cliente")

Here's my problem: When I try to add or retrieve m2m fields it obviously throws a ValueError with the message 'Proposta' instance needs to have a primary key value before a many-to-many relationship can be used.

I successfully got the wanted result by creating my obj instance with pk=0 but I'm sure it isn't the best way, if there is.

Do exist a way of doing that without cheating like this.

Any help would be great.

Thanks

otaviosoares
  • 566
  • 7
  • 17

1 Answers1

1

You might find the answers to this question helpful.

Summary for quick reference:

I might add that the documentation specifically explains how to deal with M2M fields, in the section that explains The save() method.

Of those, I recommend using ModelForms. Hopefully this helps!

Community
  • 1
  • 1
bchang
  • 1,402
  • 8
  • 19