arrayfield django example
# models.py
from django.db import models
from django.contrib.postgres.fields import ArrayField
class Product(models.Model):
name = models.CharField(max_length=255)
tags = ArrayField(models.CharField(max_length=50))
# views.py
from django.shortcuts import render
from .models import Product
def product_list(request):
products = Product.objects.all()
return render(request, 'product_list.html', {'products': products})
# product_list.html
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h1>Product List</h1>
<ul>
{% for product in products %}
<li>{{ product.name }} - Tags: {{ product.tags }}</li>
{% endfor %}
</ul>
</body>
</html>
Explanation:
1. Import necessary modules and classes:
- models.py
: Import models
from django.db
and ArrayField
from django.contrib.postgres.fields
.
- views.py
: Import render
function from django.shortcuts
and the Product
model from the current application.
Define a model (
Product
) with a CharField (name
) and an ArrayField (tags
) inmodels.py
.Create a view (
product_list
) inviews.py
that retrieves all products from the database and renders them using theproduct_list.html
template.Create an HTML template (
product_list.html
) to display the list of products. Use a loop to iterate through each product and display its name and tags.
Note: Ensure that you have PostgreSQL installed and configured in your Django project, as ArrayField
is a PostgreSQL-specific field.