簡體   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