0

Im working in two models ralated via many to many, here's the relevant code:

class Curso(models.Model):
    horarios = models.ManyToManyField(Horario, related_name = 'cursos')
    ...
    def clean(self):
       ...
       self.horarios.all()
    def save(self,*args,**kwargs):
        self.full_clean()
        ...

Horarios has been already defined, now when i try to create an of curso in the admin interface i get an error pointing to self.horarios.all():

'Curso' instance needs to have a primary key value before a many-to-many relationship can be used.

And it makes sense as it has not been saved, so my problem is, how do i access the value of horarios in the current Curso instance that is being saved?.

thanks in advance

loki
  • 2,271
  • 5
  • 32
  • 46
  • Wouldn't the Horario model have its own clean method? Why would you need to work with it in the Curso clean method? – jdi May 16 '12 at 23:12
  • @jdi horario = schedule, i need horario not to be present on some Curso instance at the same time, that's how i validate them, iteraring over them. – loki May 16 '12 at 23:38
  • Possible duplicate: http://stackoverflow.com/questions/6090859/django-instance-needs-to-have-a-primary-key-value-before-a-many-to-many-relatio – jdi May 16 '12 at 23:39

1 Answers1

2

The error seems pretty straight forward to me -- you simply cannot call a ManyToMany before an object is saved.

You can reproduce the error: Curso().horarios

Clearly you can't be doing validation on relationships that can't possibly exist, so simply wrap your call in a if self.pk

if self.pk:
   self.horarios.all()
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245