Making an array Field in Django
I need to make a model that stores the historical data of a Field, for example a poll that has a Field of its answers so it can make things with that. I was looking to the ManytoM开发者_StackOverflowany field but its too general, it feels like im doing too much for something easy.
Django 1.8 has support for an ArrayField
type that is PostgreSQL specific.
from django.db import models
from django.contrib.postgres.fields import ArrayField
class ChessBoard(models.Model):
board = ArrayField(
ArrayField(
models.CharField(max_length=10, blank=True),
size=8,
),
size=8,
)
I know it seems counter intuitive, but you definitely want to use something general like a many to one (foreign key) from your answers table to your poll table. You want your app to easily grow to support future ideas, like associating metadata with those answer-poll pairings, and being able to efficiently do queries on that metadata, like what do people in Portland answer to this question.
If you really want a deadend, dead simple, DB schema, just create an array of pks . But don't be tempted to use a postgres-only ArrayField. If you want your Django models to work with backends other than postgres (MySQL, MariaDB, or sqlite) you'll need to store your array as a string serialization. The easiest format would be a json string, but anything will do, even csv.
If you just want to store previous versions of your models you could use django-reversion, which can add version control facilities to Django models (allowing you to save revisions, rollback changes, etc).
We're using django-auditlog to do exactly what Django does recording changes through admin. https://github.com/Atomidata/django-audit-log Implemented simply by specifying any model that needs to be audited.
class MyClass(models.Model):
field1 = models.CharField(max_length=100, blank=True, db_index=True, null=True)
field2 = models.BooleanField(blank=False,null=False,default=True)
audit_log = AuditLog()
I know this doesn't answer the question directly, but I queried for "django create default arrayfield" and got here.
So, here is an example of creating an ArrayField
with a default:
from django.contrib.postgres.fields import ArrayField
def default_thing():
return ['THIS IS A DEFAULT']
class SomeModel(ParentModel):
thing_to_export = ArrayField(models.CharField(max_length=50),
default=default_thing)
精彩评论