How to save object in django database

djangodjango-modelspython-3.x

I am creating models in django, i need a field to save object, for eg to save a string django has CharField, i have api which returns me object and i want to create a model to save this object. I checked django models fields but didn't find any field to save object.

Is there any field to save an object in django database?

models.py

class UnusedResources(models.Model):
    field1 = models.CharField(max_length=20)
    field2 = models.CharField(max_length=70)
    field3 = models.CharField(max_length=70)
    saveobject = Field to save an object ?

Best Answer

A model in Django is supposed to correlate to a table in the database, so that each field in the model will actually be a field in the table for that model.

To achieve what you're trying to do, you need to create a second model, which will be the object you want to store.

from django.db import models

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

The code above was taken from the documentation, which you should definitely read for more details.

Now back to your question, the field artist inside the Album model, is actually the kind of "object" field you are looking for (it's actually a reference to another object, or a Foreign Key).

musician = Musician.objects.create(
    first_name="My", last_name="Name", instrument="guitar")
album = Album.objects.create(
    name="Great Album", release_date=date, num_stars=5, artist=musician)

As you can see, I created a Musician object called musician, and saved it to the database. Next, I created an Album object, which takes the object musician into it's artist field, and saved it into the database.

In the database, our album entry contains an artist_id field, whose value is the ID of our musician object created above.

So basically, just like we create tables for each entity we have in a database, in Django we use models, and each model corresponds to a specific table.

Related Topic