繁体   English   中英

Django 将一个由 ','(逗号)分隔的 charfield 输出拆分为一个字符串数组。?

[英]Django Split a charfield output which is seperated by ','(comma) into an array of strings.?

模板.html

{{ profile.tag }}

视图.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 本身中做到这一点?

我想要如下所示的输出需要 - 输出图像

通过在models.py文件中添加附加功能,我找到了解决问题的更好方法

模型.py

def tags_list(self):
    return self.tags.split(',')

模板.html

{% for tag in tags_list %}
    <p>{{ tag }}</p>
{% endfor %}

简单易行!

在您的视图中,像这样拆分逗号值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 %}

正确的方法有效,但我会使用list内置方法来更改数组中的字符串。

class MyModel(models.Model):
    string_array = models.CharField(max_length=100)

    def pass_to_list(self):
        return list(self.string_array)

笔记:

  • 请记住,您的字符串数组必须是数据库中的实际数组,包含 '[' 和所有内容
  • 这种方式通过使用内置的list方法起作用,但您也可以只返回由逗号分隔的字符串

暂无
暂无

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

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