我所拥有的是:
models.py:
class Address(custom_mixins.SiteAwareAbstractModel):
states = State.objects.all()
CHOICES = list()
for state in states:
CHOICES.append((state.code, state.name))
CHOICES = tuple(CHOICES)
state_name = models.CharField(max_length=80, choices=CHOICES)
然后是国家阶级
class State(models.Model):
name = models.CharField(max_length=256)
code = models.CharField(max_length=2, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-id']
def __str__(self):
return '{}'.format(self.name)
当它们存储在表中时,这将呈现所有状态。我想要的是按字母顺序显示所有状态。我试着做:
states = State.objects.all().order_by(
'name').values_list(
'code', flat=True)
但这引发了错误
CHOICES.append((state.code,state.name))
AttributeError:“ str”对象没有属性“ code”
最佳答案
尝试:
states = State.objects.all().values_list('code', 'name', named=True).order_by('name')
for state in states:
CHOICES.append((state.code, state.name))
More information on the
values_list
method关于python - django:按字母顺序对表数据进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51440046/