我是Django / Python的初级程序员,现在我正在寻找一种强大的方法来创建和更新我的模型。我希望这是一个非常普遍的问题。如何以正确的方式执行此操作的一些示例代码将非常感激。
我遇到的问题是我不确定在哪里放置save()命令。现在我有多个地方放置了save()方法。有时我必须多次点击各种视图上的保存按钮,然后才能在低级别上更改为更高级别的模型。
在本例中,我使用两个名为Medium和Circuit的简化模型。指定了两个模型的create方法以及set_medium和set_circuit方法,这显示了我当前是如何做的。
class Circuit(models.Model):
medium = models.ForeignKey('medium.Medium', related_name='medium_related', on_delete=models.CASCADE)
temperature = models.FloatField(default=60, help_text='[degC]')
glycol_percentage = models.FloatField(default=0, choices = choices.GLYCOL_PERCENTAGE)
@classmethod
def create( cls,
temperature,
glycol_percentage):
circuit = cls( temperature = temperature,
glycol_percentage = glycol_percentage)
circuit.medium = Medium.create(circuit.temperature, circuit.glycol_percentage)
circuit = circuit.set_circuit(circuit)
circuit.save()
return circuit
def set_circuit(self, circuit):
circuit.medium.glycol_percentage = circuit.glycol_percentage
circuit.medium.temperature = circuit.temperature
circuit.medium = circuit.medium.set_medium(circuit.medium)
return circuit
class Medium(models.Model):
glycol_percentage = models.FloatField(default=0, choices = choices.GLYCOL_PERCENTAGE)
temperature = models.FloatField(default=60, help_text='[degC]')
# Calculated properties
rho = models.FloatField(default=1000, help_text='[kg/m3]')
@classmethod
def create( cls, temperature, glycol_percentage):
medium = cls( temperature = temperature,
glycol_percentage = glycol_percentage)
medium = medium.set_medium(medium)
medium.save()
return medium
def set_medium(self, medium):
medium.rho = services.rho(temperature=medium.temperature, glycol_percentage=medium.glycol_percentage)
return medium
以下是我通常编写“创建和更新”视图的方法。
class CircuitCreateView(LoginRequiredMixin, CreateView):
model = Circuit
template_name = 'circuit/create.html'
form_class = CircuitForm
def form_valid(self, form):
circuit = Circuit.create( glycol_percentage = form.cleaned_data['glycol_percentage'],
temperature = form.cleaned_data['temperature'])
circuit.save()
return HttpResponseRedirect(reverse('circuit:detail', args=(circuit.id,)))
class CircuitUpdateView(LoginRequiredMixin, UpdateView):
model = Circuit
template_name = 'circuit/detail-update.html'
form_class = CircuitForm
def form_valid(self, form):
circuit = get_object_or_404(Circuit, pk=self.kwargs['pk_circuit'])
circuit.glycol_percentage = form.cleaned_data['glycol_percentage']
circuit.temperature = form.cleaned_data['temperature']
circuit = circuit.set_circuit(circuit)
circuit.save()
return HttpResponseRedirect(reverse('circuit:detail', args=(circuit.id,)))