I've read of folks talking about using ForeignKey for a One-To-Many relationship in Django, but that's not what I'm looking for. Suppose I have a model called Club defined simply as:
class Club(models.Model):
name = models.CharField(max_length = 64)
What I want is to add a field called owners that is a one-to-many relationship to users (the User model). I don't want to add a ForeignKey to User that references Club because that will clutter User. I really want a field in the Club model that maintains the relationship to 0, 1, or more Users that are considered owners of the Club. Anyone have any ideas?
What you are looking for is a Many-To-Many relationship.
In a many-to-many relationship, each row in table A can have many (zero or more) matching rows in table B, and each row in table B can have many matching rows in table A. Each club can have many owners, and each owner can have many clubs, for example.
Adapted from: http://my.safaribooksonline.com/book/databases/sql/9780321584069
Related
I have a table employees with employee_id as a primary key, some of the employees are managers and managers can also have managers.
So I wanted to add a manager_id field to the table employees which is the employee_id of the manager of the employee. I tried to create a one to many relationship between the table and itself but without success.
In the employees class I have added the following:
id_manager = models.ForeignKey(employees, on_delete=models.PROTECT)
NameError: name 'employees' is not defined
I am pretty new to django, any idea how to code this?
Thanks.
The documentation for ForeignKey covers this case explicitly:
To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE).
I'm trying to find a solution to the following problem with django models:
The app would add products to a shopping cart. The problem is that those products come from different models, and no matter where they come from, I'd like to use one ManyToManyField to incorporate them.
Suppouse I've two different kind of products from two different models:
Class ListOfProducts1(models.Model):
name= CharField()
price= IntegerField()
Class ListOfProducts2(models.Model):
name=CharField()
price=IntegerField()
The following model would be used for get the quantity and the product added(and then related to one particular order).
Here is the problem. Look to the field itemsadded, where I want to relate this field to ListOfProducts 1 and 2. I'd put both of them into the same field, but I've already know this is not possible. Just for better understanding of the problem here you have:
Class ProductsOrdered(models.Model):
itemsadded= OneToOneField(ListOfProducts1 and ListOfProducts2,on_delete=models.CASCADE)
Quantity = IntegerField()
Then the Order's model:
Class Orders(models.Model):
cart= ManyToManyField(ProductsOrdered)
The OneToOne fields can refer to only one table.
But you can use either GenericForeignKey or alternatives (which is better).
Look at this article: Avoid Django’s GenericForeignKey. It describes alternatives, such as:
nullable fields on source table
intermediate table with nullable fields
intermediate table with OneToOneFields on destination models
multi-table inheritance
multiple linked models
In my model, how do I exlicitly state that I want a ManyToMany relationship with another column to be symmetrical, so that when calling an object_set from each object, it can go through the same database table to find the relationships?
An example
class Person(models.Model):
name = models.CharField(max_length=100)
employer = models.ManyToManyField(Organization)
class Organization(models.Model):
name = models.CharField(max_length=100)
Do I need to create a second ManyToManyField in the Organization class, in order to do something like
org1.person_set.all()
to get all persons employed by the organization and
pers1.organization_set.all()
to get all of the organizations a person might work for? Or will the single ManyToManyField symmetrically make the relationships?
You don't need to do anything.
Because the ManyToMany is hosted with Person, it will be:
pers1.employer.all()
and
org1.person_set.all()
I have DB that should have one field with type Many-To-Many, but it is not and I can't change this.
For example I have a list of students and a list of subjects. Subject should be many-to-many field in students table, but as i said it is not. Students table doesn't have this field at all. But there is still another table students-subjects that contains subject_id-student_id items.
How can I embed in student form some kind of subject field that could change students-subjects data when I save a student in DB? The problem is that I can't change the DB structure so need to make it only with help of Django.
There is no such thing as a 'Many-to-many field' for a database-table like you might know it of foreign keys. In database representation many-to-many relationships are realized by using an extra table that links the primary keys (usually the ids) of the records you want to set in relation. In your case that is the table students-subjects. Django uses this table when you define a many-to-many relationship in the model. You do not have to change your database structure at all, it will be working perfectly as it is now.
See the documentation: ManyToManyField
You'll have to set the db_table option with the name of your intermediary table (i.e. students-subjects). Then everything should work fine.
EDIT:
Considering your comment, the problem is that Django expects a certain naming convention (i.e. MODELNAME_id) which isn't provided by your table. Since you say that you cannot change the table itself, you have to try something else.
You have to create an extra Model for your intermediary table (students-subjects) and define the field 'students' as a foreign key to the students model and the field 'subjects' as a foreign key to the subjects model. Then for the many-to-many field you specifiy the option 'through' with the name of your intermediary table. Set the options 'db_column' to let Django know which names you'd like to use for the databse columns. 'db_table' in the meta class is needed to specify your database table name.
You get something like:
class StudentsSubjects(models.Model):
student = models.ForeignKey(Student, db_column='student')
subject = models.ForeignKey(Subject, db_column='subject')
class Meta:
db_table = 'students-subjects'
class Student(models.Model):
...
subjects = models.ManyToManyField(Subject, through='StudentsSubjects')
...
class Subject(models.Model):
...
I hope that will help you.
For more detail see: Extra fields on many-to-many relationship.
I have clients and contacts, and each client can have any number of contacts and each contact can have any number of types. For example, client 1 can have two billing contacts, person A and person B, and two business contacts, person B and person C.
I know it would be possible to model this with the following models:
class Client(models.Model):
id #primary key
#other data
class Contact(models.Model):
id #primary key
#other data
class Relationship(models.Model):
client_id=ForeignKey(Client)
contact_id=ForeignKey(Contact)
type=CharField(max_length=255)#or some other field that represents the type
but this seems incorrect to me because the Relationship model does not represent an object but a relation between other objects. Do I need to do it this way, or is there some way of making the models so that every one actually represents the object
but this seems incorrect to me because the Relationship model does not represent an object but a relation between other objects.
A relationship is a first-class thing.
In a simple RDBMS models, the relationship was implied by a shared key (FK in one, PK in another)
However, when you have many-to-many association tables, you create an explicit row which embodies the relationship.
You're just enriching the association object with additional attributes.
This is fine. It's common, in fact.
It's a generalization of this: https://docs.djangoproject.com/en/1.3/topics/db/models/#many-to-many-relationships
Also, read this: https://docs.djangoproject.com/en/1.3/topics/db/models/#extra-fields-on-many-to-many-relationships