我已经设置了我的模型,如下所示:
Models.py
class Customer(models.Model):
CustomerID = models.CharField(max_length=50)
Name = models.CharField(max_length=50)
Mobile = models.CharField(max_length=15)
def __unicode__(self):
return self.CustomerID
class orderHistory(models.Model):
BookingNumber = models.CharField(max_length=50)
customer = models.ForeignKey(Customer)
def __unicode__(self):
return self.BookingNumber
我还使用ModelForm来设置forms.py:
class customerForm(ModelForm):
class Meta:
model = Customer
exclude = ['CustomerID']
我的views.py中的函数是这样的:
if request.method == 'POST':
form = customerForm(request.POST or None)
# check whether it's valid:
if form.is_valid():
instance = form.save()
if not instance.CustomerID:
instance.CustomerID = 'DHOBI' + instance.Mobile
instance.save()
return HttpResponseRedirect('/data/test')
else:
form = customerForm()
return render(request, "data/index.html",{'form':form})
我的问题是,在获取Customer模型的数据后,如何填充数据库中BookingNumber的数据?我的意思是,如果我想将预订号码设置为Mobile + Today的日期和时间。 我怎么做。
答案 0 :(得分:0)
import datetime
bn = "%s-%s" % (instance.Mobile,str(datetime.datetime.now())
order_hist = orderHistory.objects.create(customer=instance, BookingNumber=bn)
注意类的命名:给类大写名称和属性小写。你反过来了。