简体   繁体   中英

What is the most efficient way to create models for storing tags in Django 1.9 and Postgres 9.5?

I want to make a model where I have the option of pulling a group of items and their descriptions from a postgres database based on tags. What is the most efficient way of doing this for performance using Django 1.9 and Postgres 9.5 on data that I do not really modify often?

I found multiple ways of doing this:

Toxi solution Where 3 tables are made, one storing the item and descriptions, second storing the tags, and a third table associating tags with items. See here: What is the most efficient way to store tags in a database?

Using Array fields Where there is one table with items, descriptions, and an array field that stores tags

Using JSON fields Where there is one table with items, descriptions, and an JSON field that stores tags. The django docs mention this uses JSONB: https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/

I am guessing that using JSON fields like the following:

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

class Item(models.Model):
    name = models.CharField()
    description = models.TextField(blank=True, null=True)
    tags = JSONField()

is the most efficient for reading data but I am not really sure.

No one of theese is "most efficient", it really depends of what you're focused in.

First is classical relation approach, that provides consistency and normalisation. It also allows you to to retrieve complex information (ie give me all items with a tag T) pretty easy (but usually with a cost of joins). I think this should be your goto solution if you're using RDBMS.

Second and third (there mostly the same in your case) are easier for simple retrieve and store (ie give me all tags of an item I ), but lead to a more work for keeping your data consistent and performing complex queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM