Django: List field in model?

后端 未结 9 1583
感动是毒
感动是毒 2020-11-29 18:38

In my model, I want a field that has a list of triplets. e.g. [[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]. Is there a field that can store this data in the da

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 19:17

    If you're on Django 1.10 or newer AND Postgres as your database, you can use ArrayField. It's better to use than django-taggit or other alternatives, as it's native to the Django framework. https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#arrayfield

    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,
        )
    

    If you're on Django 3.1 or newer they've added support for JSONField with most database backends (MariaDB 10.2.7+, MySQL 5.7.8+, Oracle, PostgreSQL, and SQLite 3.9.0+). You can use this to store your Array!

    https://docs.djangoproject.com/en/3.1/ref/models/fields/#jsonfield

    from django.db import models
    
    class ChessBoard(models.Model):
        list_of_pieces = models.JSONField()
    

提交回复
热议问题