尝试通过 Web 浏览器将数据加载到 databse 中:save() 禁止以防止由于未保存的相关对象'ship'而导致数据丢失



我完全不知道为什么会出现这个错误。当我在python shell中运行类似的代码时,我从未遇到过这个错误,但当我试图通过web浏览器执行此操作时,我会遇到这个错误。知道为什么会发生这种事吗?仅供参考,我是个初学者。

型号:

from django.contrib.auth.models import User

class Hull (models.Model):
hull = models.CharField(max_length = 33, )
def __str__(self):
return self.hull
class Hull_Spec(models.Model):
ship = models.ForeignKey(Hull, on_delete=models.CASCADE)
speed = models.FloatField()
depth = models.FloatField()
remarks  = models.CharField(max_length =300)
def __str__(self):
return self.remarks

查看

def new_ship (response):
x = Hull
x.objects.create(hull = response.POST.get('ship'))
Z = Hull(hull = response.POST.get('ship'))
Z.hull_spec_set.create(speed = response.POST.get('speed'), depth = response.POST.get('depth'), remarks = response.POST.get('remarks')).save()
return HttpResponse('Success')

html用户界面


<div>
<form action = '/new_ship/' method = 'POST'> 
{% csrf_token %}
<table>
<col>
<tr>
<td><input type = 'text' name = 'ship'>Hull</input></td>
<td><input type = 'text' name = 'speed'>Speed</input></td>
</tr>
<tr>    
<td><input type = 'text' name = 'depth'>Depth</input></td>
<td><input type = 'text' name = 'remarks'>Remarks</input></td>
</tr>
<tr>
<td><input type="submit" value="Submit Fields" id = 'button_1'></td>
</tr>
</col>
</table>
</form>
</div>

您的Hull(Z(安装尚未保存到数据库中(与.save()一起(。这就是错误的原因。

您需要首先创建Hull实例(实例通常是较低(snake(的情况(:

hull = Hull.objects.create(hull = response.POST.get('ship'))

然后您可以使用它来创建一个Hull_Spec实例:

hull_spec = Hull_spec.objects.create(
hull=hull,
speed = response.POST.get('speed'), 
depth = response.POST.get('depth'), 
remarks = response.POST.get('remarks')
)

所以你的观点会变成:

def new_ship (response):
hull = Hull.objects.create(hull = response.POST.get('ship'))
hull_spec = Hull_spec.objects.create(
hull=hull,
speed = response.POST.get('speed'), 
depth = response.POST.get('depth'), 
remarks = response.POST.get('remarks')
)
return HttpResponse('Success')

另外请注意,将您的型号命名为HullSpec而不是Hull_Spec是惯例。

通常,将模型实例保存到数据库的两种方法是:

hull = Hull(hull="something")  # creates the instance
hull.save()    # saves it to the database
# or
hull = Hull.objects.create(hull="something")  # does it all in one go

最新更新