Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

model self-dependency (one-to-many field) implementation

I would like to implement a model with self-dependency. Say instance People_A may depend on People_B and People_C. I first implement this model with many to many key.

class People(models.Model):

dependency = models. ManyToManyField ('self', blank=True, null=True)

But the result is that if People_A depend on People_B will result in People_B depend also on People_A. That’s something I don’t want to have.

Then I implement it with foreign key.

class People(models.Model):

dependency = models.ForeignKey('self', blank=True, null=True)

But this doesn’t work also. If People_A depend on People_B, then no other People could depend on People_B. It will cover the old dependency with the latest dependency.

Any clue would be thankful

like image 797
user2354910 Avatar asked May 17 '13 15:05

user2354910


People also ask

How does Django implement one to many relationship?

To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).

What is _SET all Django?

_set is associated with reverse relation on a model. Django allows you to access reverse relations on a model. By default, Django creates a manager ( RelatedManager ) on your model to handle this, named <model>_set, where <model> is your model name in lowercase.

What is a many to many relationship Django?

A many-to-many relationship refers to a relationship between tables in a database when a parent row in one table contains several child rows in the second table, and vice versa.

What is foreign key in Django?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.


1 Answers

I think this is what you're looking for:

dependencies = models.ManyToManyField("self", symmetrical=False)

See the docs for symmetrical.

like image 127
Adrián Avatar answered Sep 22 '22 08:09

Adrián