我有1种形式的2个模型。在这种形式下,数据可以更改。 对于1个型号(Sloep_core),内容只需要更新,这是有效的。 对于其他模型(Sloep_gegevens),内容规范将更新。 只有价值' sloepnaam'在模型' Sloep_gegevens'的形式中更改了模型的记录' Sloep_gegevens'必须输入新记录而不更新旧记录。 save()必须从update更改为insert,但是如何?
我试图将soms代码放在一起(使用一些搜索操作)。我来到下面的代码,但现在它总是插入代码。有人有想法让它正确吗?
model.py:
class Sloep_core(models.Model):
FSN_nummer = models.IntegerField(unique=True)
HT_nummer = models.IntegerField(unique=True, blank=True, null=True)
SRNL_nummer = models.IntegerField(blank=True, null=True)
sloep_type = models.CharField(max_length=128, blank=True)
werf = models.CharField(max_length=255, blank=True)
info = models.TextField(blank=True)
objects = SloepManager()
def __str__(self):
return str(self.FSN_nummer)
class Sloep_gegevens(models.Model):
sloep = models.ForeignKey(Sloep_core, on_delete=models.CASCADE, default='')
sloepnaam = models.CharField(max_length=128)
thuishaven = models.CharField(max_length=128, blank=True)
date = models.DateField(auto_now=True)
__original_sloepnaam = None
def __init__(self, *args, **kwargs):
super(Sloep_gegevens, self).__init__(*args, **kwargs)
self.__original_sloepnaam = self.sloepnaam
def save(self, force_insert=False, force_update=False, *args, **kwargs):
if self.sloepnaam != self.__original_sloepnaam:
# then do this
force_insert = True
else:
# do that
force_update = True
super(Sloep_gegevens, self).save(force_insert, force_update, *args, **kwargs)
self.__original_sloepnaam = self.sloepnaam
class Meta:
ordering = ["date"]
def __str__(self):
return self.sloepnaam
form.py:
class SloepGegevensForm(forms.ModelForm):
class Meta:
model = Sloep_gegevens
exclude = ['pk', 'sloep']
class SloepCoreForm(forms.ModelForm):
class Meta:
model = Sloep_core
exclude = ['pk', 'SRNL_nummer']
views.py:
def sloep_edit(request, pk):
sloep = Sloep_core.objects.get(pk=pk)
sloep_sg = Sloep_gegevens.objects.filter(sloep=pk).order_by('-date')[0]
if request.method == "POST":
formSG = SloepGegevensForm(request.POST)
formSC = SloepCoreForm(request.POST, instance=sloep)
if all([formSG.is_valid(), formSC.is_valid()]):
sloep = formSC.save()
SG = formSG.save(commit=False)
SG.sloep = sloep
SG.save()
return redirect('sloep_detail', pk=sloep.pk)
else:
formSG = SloepGegevensForm(instance=sloep_sg)
formSC = SloepCoreForm(instance=sloep)
return render(
request,
'sloepen/sloep_edit.html',
{'formSG': formSG, 'formSC': formSC,})
答案 0 :(得分:0)
我找到了问题的答案。在视图中,我没有在POST request.model中给出带有SloepGegevensForm的pk。
我将formSG = SloepGegevensForm(request.POST)
更改为formSG = SloepGegevensForm(request.POST, instance=sloep_sg)
这使save()工作。