首页 > 解决方案 > 如何将 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} (...)'

标签: djangodjango-modelsdjango-views

解决方案


你可以试试这个:

"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)

推荐阅读