如何从Django Queryset返回元组中的特定信息
我有一个简单的模型,其中一个元组返回如下信息:如何从Django Queryset返回元组中的特定信息,django,django-models,django-queryset,Django,Django Models,Django Queryset,我有一个简单的模型,其中一个元组返回如下信息: class Store(models.Model): STORE_BRAND = ( ('nike', 'Nike'), ('adidas', 'Adidas'), ('puma', 'Puma'), ) online_store = models.CharField(unique=True, max_length=255, choices=STORE_BRAND) def __str__(self): retur
class Store(models.Model):
STORE_BRAND = (
('nike', 'Nike'),
('adidas', 'Adidas'),
('puma', 'Puma'),
)
online_store = models.CharField(unique=True, max_length=255, choices=STORE_BRAND)
def __str__(self):
return self.online_store
我试图返回存储名称,以便在上下文处理器的条件语句中使用它
store_brand = Store.objects.get(online_store='nike')
工作正常,返回
<Store: nike>
我做错了什么?您正在使用对象引用属性。您应该使用正确的属性来引用要访问的值
>>> store_brand = Store.objects.get(online_store='nike')
>>> store_brand.online_store == 'nike' # the attribute online_store
True
>>> store_brand.__str__() == 'nike' # since you defined __str__ to return the required attribute, you can use this too
True
嗯,
store\u brand
是一个store
对象,而不是字符串。您可以通过store\u brand.online\u store==“nike”
查看。
>>> store_brand = Store.objects.get(online_store='nike')
>>> store_brand.online_store == 'nike' # the attribute online_store
True
>>> store_brand.__str__() == 'nike' # since you defined __str__ to return the required attribute, you can use this too
True