And with that, it will create the two tables and the persons table will have
a field referencing the id field of the cities table.
Every field that refers to a relationship must be placed inside the method.
relationships, as this method is only executed after all tables are created.
As is done in the last line, it creates all the tables and then starts doing
the relationships.
Note
You may have also noticed the method relationships in the City class,
but what will this do?
This method doesn't make any changes to the database, just
adds the persons: OneToMany field to the class, this field has some methods
which are explained here.
ManyToMany
To create a Many to Many relationship we also use the ForeignKey field.
First we create the User and WorkingDay tables, they have a Many to Many
relationship. To represent this relationship we create a third UsersWorkingDay
table that has a reference to the PK of the other two tables, and thus
creating the relationship.
Note
The relationships method in the two tables: User and WorkingDay are a little bit
different from the previous example. Have the @classmethod signaling that it is a
method of the class and not the instance, so it creates the users and
working_day in both models.
With that allowing some methods to be executed,
like: User add a relationship with WorkingDay without using the
UsersWorkingDay model. More examples can be seen here.
OneToOne
To represent the One to One relationship, just make use of the OneToOne field.
We create the Person table and the Contact table. We use the OneToOne field.
This field will be the PK of that table, being of the same type as the table in the
relationship, in this case the same type as the PK of the Person model.
And with that, DuckORM will save the relationship contact record
with this person. What happens if I try to save the same person again in a
another contact?
1234
contact_error=Contact(phone="YYYYYYYYY-YYYY",id_person=person_1)awaitContact.save(contact_error)# This line will throw a duplicate # record exception.