Search code examples
jsondjangomongodbpostgresqlnon-relational-database

Non-relational database schema for Django with postgres


My Django project uses postgresql 9.4, which supports JSON fields. I would like to switch from a relational to a (partly) non-relational schema using these fields.

Say I have models Foo and Bar and each object Bar belongs to exactly one Foo. Currently, I use a ForeignKey from Bar to Foo to model this, but I would like to switch to storing the Bar objects directly inside Foo as a list of model instances. With postgresql, I can use a JSONField in Foo which would store a list of JSON representations of Bar objects, but then I would have to deal with serialization to JSON manually.

The MongoDB ORM for Django provides the Django fields to do that in a clean way:

class Foo(models.Model):
    bar_list = ListField(EmbeddedModelField('Bar'))

Is there a way to have a similar functionality with the postgres backend?


Solution

  • Nesting data objects within each other is a very Non-relational database approach that is not recommended and is going to cause performance issues in a relational database.

    You will have a few problems if you try this in postgres:

    1. Your querying abilities on the nested JSON data will be limited to text only.
    2. Forget about sorting, aggregation and such for the nested data.
    3. You will have to deal with serialization when you need the nested data and before you send back to the database to save.
    4. Making changes to the nested models will become very python heavy since you're basically circumventing all the good integrity checks that relational databases have and the nice checks that Django has for types and such.
    5. Querying will become slower because you will have to retrieve every nested object for every Foo you query since there isn't a way to limit the amount of nested objects like you can in Mongo.

    The recommendation here is to stick with one database type Relational or Non-relational and do what works good on either one.

    If you need Postgres use Foreign keys and if you use Mongo use nested objects.