Jakub
Jakub

Reputation: 303

Django - make createview save two different models

i am trying to get django automatically create instance of 2nd model while creating 1st via CreatView:

models.py

class MAG_magazyn(models.Model): #1st
  nr_ident=models.CharField(max_length=50, unique=True)
  nazwa=models.CharField(max_length=50)
  typ=models.CharField(max_length=50, blank=True, null=True)
  podzespol=models.BooleanField(default=False)
  kategoria=models.ForeignKey(MAG_kategorie_czesci)

class MAG_magazyn_stan(models.Model): #2nd
  id_czesc=models.OneToOneField(MAG_magazyn)
  regal=models.CharField(max_length=3)
  polka=models.CharField(max_length=3)
  stan_min=models.IntegerField()
  stan=models.IntegerField()
  alert=models.IntegerField(default=0)
  rel_stan=models.DecimalField(...)

Now, as those models are connected i would like to add instance of 2nd with some default values. My idea was to override form_valid, get last id of 1st model and then create and save 2nd instance :

  Class NowyMag (CreateView):
'''
Widok pozwalajacy na dodanie nowej czesci magazynowej do listy
'''

model=MAG_magazyn
fields=[
        (...),
        ]
template_name='magazyn/nowy_mag.html'
success_url=reverse_lazy('mag_lista_mag')

  def form_valid(self, form):
     form.save(  )
     nowy_stan=MAG_magazyn_stan(id_czesc=MAG_magazyn.objects.latest('id').id, regal=0,polka=0,stan_min=0,stan=0, alert=1)
     nowy_stan.save()
     return super(NowyMag, self).form_valid(form)

but all i got is:

Exception Type: ValueError
Exception Value: Cannot assign "20": "MAG_magazyn_stan.id_czesc" must be a "MAG_magazyn" instance.

Am I thinking correctly, but have mistake, or there is some cleaner way to get something like this working ?


a little bit of better explanation: While creating instance of MAG_magazyn, i would like to automatically create MAG_magazyn_stan with id of created MAG_magazyn and some default values( here all equal to 0)

Upvotes: 1

Views: 1407

Answers (1)

dkarchmer
dkarchmer

Reputation: 5594

Your question is not very clear, but I am assuming you are using a Form associated to MAG_magazyn, in which case, you want to do something like:

def form_valid(self, form):
    # You need to get a new object based on the form
    self.object = form.save(commit=False)
    ... # in case you want to modify the object before commit
    self.object.save()
    # not you can use it to assign to the second model
    nowy_stan=MAG_magazyn_stan(id_czesc=self.object, ...)
    nowy_stan.save()

    return HttpResponseRedirect(self.get_absolute_url) # or elsewhere

Upvotes: 3

Related Questions