I have django app where technicians enter service data, and if the customer is not in the list they choose "NEW" from the customer
field dropdown and enter the new customer's name in the service.new_customer
field rather than adding the customer. When I display it, I want to show "John's Pub" if it's an existing customer, and "NEW: John's Pub" if it's not. I can get this to work by using the id - the id for the customer called "NEW" is 1038. But, I want to be able to have the logic reference the word "NEW" rather than the id.
Here is my models.py
class Service(models.Model):
customer = models.ForeignKey(Customer)
new_customer = models.CharField(max_length=100, blank=True, null=True)
class Customer(models.Model):
name = models.CharField(max_length=200)
This view.py
works:
def service_view(request):
for service in services:
if service.customer_id == 1038:
service.customer_combo="%s:%s"%(service.customer,service.new_customer)
else:
service.customer_combo="%s"%(service.customer)
return render(request,'template.html')
This view.py
does not work*:
def service_view(request):
for service in services:
if service.customer == 'NEW':
service.customer_combo="%s:%s"%(service.customer,service.new_customer)
else:
service.customer_combo="%s"%(service.customer)
return render(request,'template.html')
How should I be constructing the 'if service.customer == 'NEW':' statement to get it to work?
if service.customer.name == 'NEW':
You are trying to compare a Customer
object with the name
of the customer. They are of different types and cannot be compared.
You need to do something like:
service.customer == some_customer_object # compare with model object
or
service.customer.name == 'NEW' # compare with the name
or
str(service.customer) == 'NEW' # compare with the representation of the object
这也有效,但我认为彼得的答案更好,只是看起来更干净
if str(service.customer) == 'NEW':
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.