Python Django分割由';分隔的charfield输出';(逗号)转换为字符串数组。?
template.htmlPython Django分割由';分隔的charfield输出';(逗号)转换为字符串数组。?,python,django,django-templates,Python,Django,Django Templates,template.html {{ profile.tag }} {% for tag in tags_list %} <p>{{ tag }}</p> {% endfor %} views.py class ProfileView(CanEditMixin, UserPassesTestMixin, DetailView): template_name = "profile/profile_view.html" queryset = User.ob
{{ profile.tag }}
{% for tag in tags_list %}
<p>{{ tag }}</p>
{% endfor %}
views.py
class ProfileView(CanEditMixin, UserPassesTestMixin, DetailView):
template_name = "profile/profile_view.html"
queryset = User.objects.all()
context_object_name = 'profile'
slug_field = "username"`
输出为“tag1、tag2、tag3”
django本身有没有办法做到这一点
我希望输出如下所示在您的视图中,按如下方式拆分逗号值
CharField
字段:
class ProfileView(CanEditMixin, UserPassesTestMixin, DetailView):
template_name = "profile/profile_view.html"
queryset = User.objects.all()
context_object_name = 'profile'
slug_field = "username"`
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) # get parent context
# the model here should be replaced with the object that has the "tag" attribute. DO NOT use the "model" word.
# Try self.object.tag.split(',')
tag_list = model.tag.split(',') # conversion from a string to a list
context['tag_list'] = tag_list # add to the context the tag_list list
return context
然后在模板中,只需对其进行迭代:
{% for tag in tag_list %}
<p>{{ tag }}</p>
{% endfor %}
{%for tag_list%}
{{tag}}
{%endfor%}
通过在models.py
文件中添加附加函数,我找到了解决问题的更好方法
models.py
def tags_list(self):
return self.tags.split(',')
template.html
{{ profile.tag }}
{% for tag in tags_list %}
<p>{{ tag }}</p>
{% endfor %}
{%for tags in tags\u list%}
{{tag}}
{%endfor%}
简单易用 正确的方法是可行的,但我会使用
list
内置方法来更改数组中的字符串
class MyModel(models.Model):
string_array = models.CharField(max_length=100)
def pass_to_list(self):
return list(self.string_array)
笔记:
- 请记住,字符串数组必须是数据库上的实际数组,包含“[”和所有内容
- 这种方法通过使用内置的
方法来工作,但也可以只返回用逗号分隔的字符串list
'cat1,cat2,cat3'
转换为['cat1','cat2','cat3']
?当您必须存储字符串数组时,背后的想法会有所帮助,但您使用的是mysql,但如果您使用的是postgres,我强烈建议您使用