Python 引用外键的if语句
我有一个django应用程序,技术人员可以在其中输入服务数据,如果客户不在列表中,他们可以从Python 引用外键的if语句,python,django,Python,Django,我有一个django应用程序,技术人员可以在其中输入服务数据,如果客户不在列表中,他们可以从customer字段下拉列表中选择“NEW”,并在service.NEW\u customer字段中输入新客户的姓名,而不是添加客户。当我显示它时,如果它是现有客户,我想显示“John's Pub”,如果不是,我想显示“NEW:John's Pub”。我可以通过使用id来实现这一点——名为“NEW”的客户的id是1038。但是,我希望能够让逻辑引用单词“NEW”,而不是id 这是我的models.py c
customer
字段下拉列表中选择“NEW”,并在service.NEW\u customer
字段中输入新客户的姓名,而不是添加客户。当我显示它时,如果它是现有客户,我想显示“John's Pub”,如果不是,我想显示“NEW:John's Pub”。我可以通过使用id来实现这一点——名为“NEW”的客户的id是1038。但是,我希望能够让逻辑引用单词“NEW”,而不是id
这是我的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)
此view.py
工作:
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')
此view.py
不起作用*:
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')
- 当我说它不起作用时,我的意思是它只在“else”条件下分配customer.combo,尽管在很多情况下客户是新的-它打印的是“NEW”而不是“NEW:John's Pub”
我应该如何构造'if service.customer=='NEW':'语句以使其工作?
if service.customer.name=='NEW':
您试图将客户
对象与客户的名称
进行比较。它们属于不同类型,无法进行比较
您需要执行以下操作:
service.customer == some_customer_object # compare with model object
或
或
这也行得通,但我认为彼得的答案更好,只是看起来更干净而已
if str(service.customer) == 'NEW':
这很有道理,谢谢你指出这一点。我经常被这件事缠住。
str(service.customer) == 'NEW' # compare with the representation of the object
if str(service.customer) == 'NEW':