我正在尝试使用“update()”来更新“ModelC”数据库中的现有数据。
型号:
from django.db import models
class ModelA(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
def __str__(self):
return '%s' %(self.id)
class ModelB(models.Model):
observation = models.CharField(max_length=30)
status = models.BooleanField()
relation = OneToOneField(ModelA)
def __str__(self):
return '%s' %(self.relation)
class ModelC(models.Model):
relationA = models.ForeignKey('ModelA', null=True, blank=True)
date_relationA = models.CharField(max_length=10, null=True, blank=True)
user_relationA = models.CharField(max_length=15, null=True, blank=True)
relationB = models.ForeignKey('ModelB', null=True, blank=True)
date_relationB = models.CharField(max_length=10, null=True, blank=True)
user_relationB = models.CharField(max_length=15, null=True, blank=True)
def __str__(self):
return str(self.id)
ModelA的观点:
def RegModelA(request):
form = ""
user = None
if request.method == "POST":
form = ModelAForm(request.POST)
if form.is_valid():
save = form.save()
date = time.strftime("%d - %m - %Y")
user = request.user.username
create = ModelC.objects.create(relationA=save, date_relationA=date, user_relationA=user, relationB=None, date_relationB=None, user_relationB=None)
return redirect('/')
else:
form = ModelAForm
return render(request, "ModelA.html", {"form":form})
在ModelA中:
在ModelC中:
ModelB的观点:
def RegModelB(request):
form = ""
user = None
if request.method == "POST":
form = ModelBForm(request.POST)
if form.is_valid():
save = form.save()
date = time.strftime("%d - %m - %Y")
user = request.user.username
update = ModelC.objects.filter().update(relationB=save, date_relationB=date, user_relationB=user)
return redirect('/')
else:
form = ModelBForm
return render(request, "ModelB.html", {"form":form})
我在寻找的是,当注册ModelB的数据时,ModelC中关系B的字段会被更新。
但是如果ModelB的关系等于ModelC中的字段relationA,我就找不到如何获取ModelC的ID。
我正在使用:
Python 3.5
Django 1.11