0

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?

2
  • What do you mean by save class array in class? You don't save classes - you save objects. And where is your code? What have you tried? Sorry, but your question is unclear and you seem to be missing some fundamentals of Django. Commented Jul 10, 2012 at 7:24
  • I have been working on java/hibernate.My query was like in java(POJO classes) for eg. we have a POJO class Class Company{ int id , String name , Employee[] employee with getter/setter methods}.Employee is another Pojo class with its related data.I want to recode using the django models.How do I proceed ? Commented Jul 10, 2012 at 7:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I have gone through the Django tutorial and as well as how the ORM works.My doubt is how do I represent an array of object in database using django models.I am sorry as to I couldn't explain the question correctly earlier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.