如何从Django PostgreSQL ArrayField获取字符串?

时间:2019-06-20 06:00:10

标签: python django python-3.x postgresql django-models

我正在尝试从数据库中的ArrayField中获取一个字符串,但是它仅按字符显示,而不是完整字符串。例如,ArrayField被命名为words,并且在数据库中显示为{word1, word2, word3},因此在HTML中,我将{{ object.words.0 }}{呈现在屏幕上。

如何获取它来渲染word1

我已将django.contrib.postgres添加到INSTALLED_APPS。 这就是我的模型中的样子:

from django.db import models
from django.contrib.postgres.fields import ArrayField

class WordArr(models.Model):
     words = ArrayField(models.CharField(max_length=200, null=True))

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,这是我的数据库造成的。我模型中的ArrayField以前是我更改过的CharField。我以为迁移是正确的,但是数据库仍将其作为CharField读取,因此输出是字符串的第一个字符。我迁移到新数据库,一切正常。我的代码如下,以供进一步参考:

models.py

from django.db import models
from django.contrib.postgres.fields import ArrayField

# Create your models here.
class Word(models.Model):
    first = models.CharField(max_length=50)
    last = models.CharField(max_length=50)
    words = ArrayField(models.CharField(max_length=50, null=True))

    def __str__(self):
        return self.first

views.py

from django.shortcuts import render
from django.views.generic.detail import DetailView
from django.views.generic import CreateView
from .models import Word

# Create your views here.
class ArrayCreateView(CreateView):
    model = Word
    fields = ['first', 'last']
    success_url = '/'

    def form_valid(self, form):
        w = form.save(commit=False)
        random_words = ["word1", "word2", "word3"]
        w.words = random_words

        return super().form_valid(form)

class ArrayDetailView(DetailView):
    model = Word   

word_form.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>Create Array</h1>
    <div>
        <form method="POST">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Submit</button>
        </form>
    </div>
</body>
</html>

word_detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>{{ object.words.0 }}</h1>
</body>
</html>

settings.py

INSTALLED_APPS = [
     ...
     'django.contrib.postgres',
     'arr',
]

urls.py

from django.contrib import admin
from django.urls import path

from arr.views import ArrayCreateView, ArrayDetailView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('create/new/', ArrayCreateView.as_view(), name='create'),
    path('detail/<int:pk>/', ArrayDetailView.as_view(), name='detail')
]