我有一个客户模型:
class Customer(models.Model):
Name = models.TextField(blank=False)
Surname = models.TextField(blank=False)
PhoneNumber = models.TextField()
Address = models.TextField()
SendSms = models.BooleanField(default=True)
SendEmail = models.BooleanField(default=True)
Email = models.TextField()
@classmethod
def create(cls, name, surname, phoneNumber, address , sendSms, sendEmail, email):
customer = cls(Name=name, Surname = surname, PhoneNumber = phoneNumber
, Address = address, SendSms = sendSms, SendEmail = sendEmail
, Email = email)
return customer
引用this doc,这就是我如何创建新对象。
我有一个表单来创建新客户。像这样工作:
class NewCustomer(View):
def get(self, request):
c = {}
c.update(csrf(request))
return render_to_response("Customer/NewCustomer.html", c)
def post(self, request):
customer = Customer.create(request.POST.get("name", ""), request.POST.get("surname", ""),
request.POST.get("PhoneNumber", ""), request.POST.get("Address", ""),
request.POST.get("SendSms", ""), request.POST.get("SendEmail", ""),
request.POST.get("Email", ""))
return HttpResponseRedirect("/Customers/",{"customerId":customer.id})
我有另一个视图女巫列出所有客户,但我在该视图中得到空数组。
def AllCustomers(request):
return render_to_response("Customer/AllCustomers.html", {"customers": Customer.objects.all()})
有人能指出我在这里缺少什么来创造对象吗?
答案 0 :(得分:2)
您需要致电save
method以实际记录:
customer = cls(Name=name, Surname = surname, PhoneNumber = phoneNumber
,Address = address, SendSms = sendSms, SendEmail = sendEmail
,Email = email)
customer.save()
return customer
或需要使用Model.objects.create(..)
:
customer = cls.objects.create(
Name=name, Surname = surname, PhoneNumber = phoneNumber
,Address = address, SendSms = sendSms, SendEmail = sendEmail
,Email = email)
return customer
答案 1 :(得分:1)
最好的选择是使用Django的ORM create method。但是,如果要覆盖此方法,请添加一些功能。您应该使用Manager
class CustomerManager(models.Manager):
def create(self, **kwargs):
super(CustomerManager, self).create(**kwargs)
# Here it goes custom code
然后你应该参考Model
中的Managerclass Customer(models.Model):
objects = CustomerManager()
Name = models.TextField(blank=False)
...