我拥有的是:
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”
答案 0 :(得分:2)
尝试:
states = State.objects.all().values_list('code', 'name', named=True).order_by('name')
for state in states:
CHOICES.append((state.code, state.name))