django - 如何将 django 模型中的数据更新为视图中的标题大小写?
问题描述
我试图在views.py或models.py中将数据库中的“HOSPITAL ZERO”、“HOSPITAL ONE”等字符串列更改为标题大小写或“Hospital zero”。我都试过了,都不能为我工作。
这是我在views.py 中的代码。列在名称下的医院模型中,即 Hospital.name。
def results(request):
if request.method == "GET":
Q=()
out_words = request.GET.get('s')
context = RequestContext(request)
#here is where I tried to change it
qs = Price.objects.annotate(hospital__name=Lower('hospital__name'))
table = PriceTable(qs.filter(service__desc_us__icontains = out_words))
RequestConfig(request, paginate={'per_page': 10}).configure(table)
RequestConfig(request).configure(table)
else:
table = PriceTable(Price.objects.all())
RequestConfig(request).configure(table)
return render(request, 'results.html', {'table': table})
这是我在 model.py 中尝试的方法。
class Hospital(models.Model):
"""Model representing Hospitals."""
hid = models.CharField(max_length = 8, null=True)
name = models.CharField(max_length=200, primary_key=True)
hopid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular hospital in database')
address = models.CharField(max_length = 200, null = True)
class Meta:
ordering = ['hopid']
#here is where i tried to update it
def save(self, *args, **kwargs):
self.name = self.name.title()
return super(Hospital, self).save(*args, **kwargs)
def __str__(self):
"""String for representing the Model object."""
return f'{self.name} ({self.address})'
class Price(models.Model):
"""Model with all the hospital prices by service."""
priceid = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular service in database')
comments = models.CharField(max_length = 200, blank = True, null =True)
hospital = models.ForeignKey("Hospital", on_delete=models.SET_NULL, null=True)
class Meta:
ordering =['priceid']
def __str__(self):
return f'{self.hospital.name} (...)'
解决方案
你可以试试这个:
"HOSPITAL ONE".lower().capitalize()
my_string.lower().capitalize()
这是一个选项:
def save(self, *args, **kwargs):
self.name = self.name.lower().capitalize()
return super(Hospital, self).save(*args, **kwargs)
推荐阅读
- openfaas - 有没有办法为部署的功能指定日志记录驱动程序
- php - 单击删除按钮时如何从文件夹中删除图像
- android - 不能让 listview 它说数组为空
- javascript - Node.js 在函数中查看对象以及为什么对象的属性未定义
- java - 如何从 URI 中删除片段
- python - 登录并下载 - Python 请求
- python - 分组和组合字符串
- node.js - electron-forge:缺少依赖项 = git 和节点,但我可以选择哪个 git?
- c# - 如何将用户选择的值存储到由 SharePoint Web 部件呈现的 n DropDown 中?
- r - nnfor 包中的 elm 函数无法识别 xreg 的输入