[英]Django - make createview save two different models
i am trying to get django automatically create instance of 2nd model while creating 1st via CreatView: 我试图让Django在通过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. 现在,随着这些模型的连接,我想添加一些具有默认值的2nd实例。 My idea was to override form_valid, get last id of 1st model and then create and save 2nd instance :
我的想法是重写form_valid,获取第一个模型的最后一个ID,然后创建并保存第二个实例:
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) 更好的解释:在创建MAG_magazyn的实例时,我想自动创建具有创建的MAG_magazyn的ID和一些默认值的MAG_magazyn_stan(这里都等于0)
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: 您的问题不是很清楚,但是我假设您使用的是与
MAG_magazyn
关联的表单,在这种情况下,您想要执行以下操作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.