how to store other model fields in a model field in django

27 Views Asked by At

hi i reacently learnd django and i don't have much experience with it and i ran into a problem this is my main model

class food(models.Model):
    name = models.CharField(max_length= 255)
    category = models.ForeignKey('resturant.category', models.DO_NOTHING, db_column='category')
    picture = models.ImageField(upload_to='/images/', default=None)
    rank = models.IntegerField()
    price = models.BigIntegerField()
    ingredients = models.ManyToManyField(storage)
    discription = models.TextField()
    

    def __str__(self) -> str :
        return f'{self.id} - {self.name}'

and this is another model in another app

class storage(models.Model):
    name = models.CharField(primary_key=True,max_length=255)
    count = models.IntegerField()
    type = models.CharField(max_length=255,null=True)
    
    def __str__(self) -> str :
        return f'{self.name}'

and i want to store all the fields in storage model inside the food.ingredients field somthing like an array of objects it should be

right now when i make the api of get_all_food on food model it will return

[
  {
    "name": "food_name1",
    "category": 2,
    "picture": "/images/IMAG0030.jpg",
    "rank": 12,
    "price": 450001,
    "ingredients": [
      "rice",
      "onien",
      "vegi",
      "salt",
      "tomato",
      "meat",
      "lemon"
    ],
    "discription": "gsdgsgfsfg"
  },
  {
    "name": "food_name2",
    "category": 3,
    "picture": "/mehrbanoo/images/IMAG0075.jpg",
    "rank": 28,
    "price": 50000,
    "ingredients": [
      "rice",
      "vegi",
      "beans",
      "lemon"
    ],
    "discription": "ssdafafadsada"
  }
]

but i need it to be like :

[
 {
    "name": "food_name2",
    "category": 3,
    "picture": "/mehrbanoo/images/IMAG0075.jpg",
    "rank": 28,
    "price": 50000,
    "ingredients": [
      {
         "rice",2,gr
      }
      {
         "vegi",3,gr
      }
      {
         "beans",5,gr
      }
      {
         "lemon",6,gr
      }
    ],
    "discription": "ssdafafadsada"
  }
]

is it possible?

0

There are 0 best solutions below