user1513944
user1513944

Reputation: 1

how to store an array of class in django model

Lets say I have to save a class array in a particular class in django.how do i proceed? for eg.I have a class Books.I wish to store thriller books array in the class books.what is the syntax for Django model and database tables?

Upvotes: 0

Views: 1378

Answers (1)

freakish
freakish

Reputation: 56467

Have you read the Django tutorial? Everything is explained there. The answer may actually depend on the database you are using, though. But assuming you use classical SQL, then here's how ORM works:

1) You define main model:

class Company( models.Model ):
    name = models.CharField( max_length = 100 )
    # some other fields if necessary

2) You define the corresponding submodel which points to the main model:

class Employer( models.Model ):
    name = models.CharField( max_length = 100 )
    company = models.ForeignKey( Company )  # <----- relation here
    # some other fields if necessary

3) If you have an object comp of type Company, then you can access all employers of that company using:

comp.employer_set.all( )

The employer_set property comes from the name of Employer class combined with _set suffix. You may define your own name for this field. You just need to modify the definition of Employer class a bit, like this:

class Employer( models.Model ):
    name = models.CharField( max_length = 100 )
    # note the change
    company = models.ForeignKey( Company, related_name = 'employers' )

Now you can use:

comp.employers.all( )

These are the basics. It is impossible (or at least extremely inefficient) for relational database to actually create the array of references in the main model. However that's not the case if you are using some nonrelational database like MongoDB.

Upvotes: 1

Related Questions