django选择字段返回索引但不是实际名称

时间:2018-02-10 13:44:02

标签: django django-models

我的 models.py

WebFieldType.objects.all().values('webfield_type')

如果我愿意,现在在shell中:

[{'webfield_type' : 'FACEBOOK'}, {'webfield_type' : 'INSTAGARAM'}],它正在返回WebTokens.objects.all().values('token_name','web_field_type')

但如果我愿意的话 [{'token_name' : 'some_token_name', 'web_field_type' : 1}]它正在返回

'{}'.format(self.get_webfield_type_display())

正如你在web_field_type中看到的那样,它返回了id,但我需要名字。 甚至尝试在WebTokens模型中使用return let musicType = ["Blues", "Klasik", "Halk", "Hip-hop", "Caz", "Pop", "Rock", " Enstrümantal", "House", "Rap" , "Slow"] func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return musicType.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath as IndexPath) as! CustomCell cell.nameLabel.text = musicType[indexPath.item] cell.sizeToFit() return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // let cell = collectionView.cellForItem(at: indexPath) as? CustomCell let text = NSAttributedString(string: musicType[indexPath.item]) print(musicType[indexPath.item]) print(" - ") print(text.size()) let width = (text.size().width) * 2 let height = CGFloat(40) return CGSize(width: width, height: height) } } class CustomCell: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) setupView() } let nameLabel: UILabel = { let lbl = UILabel() lbl.translatesAutoresizingMaskIntoConstraints = false return lbl }() func setupView(){ backgroundColor = UIColor.red addSubview(nameLabel) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel])) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } 但是徒劳无功。

所以基本上我需要在调用它时存储在WebTokens模型中的所有内容。

1 个答案:

答案 0 :(得分:0)

您未在template_name模型中指定WebTokens属性。但我会尽力说明你的观点。正在做的是你从ManyToMany字段中获取值web_field_type: 1。因此,如果你想从模型中获取所有的vallu并将其序列化,那么它将比这更复杂。考虑在WebTokens模型中创建方法。

<强> EDITED

@property
def web_field_type_types(self):
    names = list()
    for obj in self.web_field_type.all():
        names.append(obj.get_type_display())
    return str(names)

然后在查询中使用它,以便您可以使用

获取ID字符串
webtoken.web_field_type_types