Tuesday, October 29, 2013

Re: django difference between - one to one, many to one and many to many


On Tue, Oct 29, 2013 at 12:36 AM, Aamu Padi <aamupadi@gmail.com> wrote:
>
> So, this is my first time learning computer language. And I chose python and django. Now, I got many of the basic concepts of python and also django. I can create new page with the views and all other stuff. But I am still confused with the relations, i.e. one to one, many to one, and many to many. Will someone please please please explain it to me. How can I use it? I really need to know

many to one :
This relationship is used as foreign key. In this one table can be used as a parent for many children.
Eg :

class Manufacturer(models.Model):
    # ...
    pass

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    # ...

class Bus(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    # ...


Here there is one base table Manufacturer which acts as base for 2 other tables.

many to many :
When you want many rows of a table to be linked to many rows of another table, we use manytomany field.

class Vehicle(models.Model): 
   # ..
   manufacturer = models.ManyToManyField(Manufacturer)

Application : For making checkboxes

one to one :
This is similar to foreign key, except that one parent has only one child.
Conceptually, this is similar to a ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.

class Car(models.Model):
    manufacturer = OneToOneField('Manufacturer')
    # ...


Hope this helped.



--
Sandeep Kaur
E-Mail: mkaurkhalsa@gmail.com
Blog: sandymadaan.wordpress.com



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAF66xG01aUyofi4jTRnpTzvne8Ao2Aiczm8DTEfa_TAUw%2B%3DOSA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment