Home > Back-end >  How to design ArrayField in django rest framework?
How to design ArrayField in django rest framework?

Time:10-31

I am making API for cook book with Django Rest Framework. I don't know how to design ingredients model to make data to be like this:

{
        "id": 1,
        "name": "spaghetti",
        "recipe": "recipe",
        "ingredients": [
            [{name:'pasta',amount:100},{name:'tomato',amount:200},{...}]
        ],    
    }

My model:

class Meal(models.Model):
    name = models.TextField()    
    recipe = models.TextField()
    ingredients = ?

Also how to serialize this field?

CodePudding user response:

I believe what you are looking for is JsonBField

from django.contrib.postgres.fields.jsonb import JSONField as JSONBField
ingredients = JSONBField(default=list,null=True,blank=True)

this should do what you expect, have a nice day

edit: thanks for the update as @Çağatay Barın mentioned below FYI, it is deprecated, Use django.db.models.JSONField instead.see the Doc

CodePudding user response:

from , Django comes with JSONField

class Meal(models.Model):
    name = models.TextField()
    recipe = models.TextField()
    ingredients = models.JSONField()
  • Related