简体   繁体   English

从 Django 中的模型类生成可迭代的选择元组

[英]Generate iterable choices tuple from model class in Django

I'm working on a django model and I want to generate a tuple out of my model instances :我正在研究 django 模型,我想从我的模型实例中生成一个元组:

model.py模型.py

class Extra(models.Model):
    extra_n = models.CharField(max_length=200)
    extra_price = models.IntegerField(default=0)
    def __str__(self):
       return self.extra_n

The output I'm expecting based on the user entries on the form associated :我期望的输出基于关联表单上的用户条目:

choices = (('extra_price 1','extra_n1'),
           ('extra_price 2','extra_n2'),
           ('extra_price 3','extra_n3')
)

You can make an ORM call with .values_list(..) [Django-doc] :您可以使用.values_list(..) [Django-doc]进行 ORM 调用:

tuple(Extra.objects.values_list('extra_price', 'extra_n'))

That being said, Django forms can work with a ModelChoiceField [Django-doc] that will make choices itself based on the model (or a filtered queryset if you provide one).话虽如此,Django 表单可以与ModelChoiceField [Django-doc] 一起使用,它会根据模型(或过滤的查询集,如果您提供的话)自行做出选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM