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?
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:
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.