Many2many relation in Odoo 10 (python) - python

I have to create a STudent Management module by Odoo 10.0 in windows. So I'd like to know exactly how to establish a "many2many" relation in Odoo (not Openerp). I have searched a lot of solutions on the Internet, but I don't understand clearly them :
enter image description here
For example, there are 2 classes (Student and Course) following with their attributes :
class Student(models.Model):
_name = "management.student"
IdStudent = fields.Integer() #primary key
Name = fields.Char()
Gender = fields.Char()
Address = fields.Char()
class Course(models.Model):
_name = "management.course"
IdCourse = fields.Integer() #primary key
course = fields.Char()
credit = fields.Integer()
professor = fields.Char()
Thanks a lot for your help !

Many2many relations in Odoo are best described as many records of one model can be linked to many records of another model. To use your example many classes can have many students and students can have many classes, hence many2many. As apposed to many2one such as an apple can only have only one tree or one2many one tree can have many apples.
To define a many2many relationship for Courses and Students you can create a field on the course like this. (taken from the docs)
attendee_ids = fields.Many2many('management.student', string="Attendees")
In this case because you have not specified the optional arguments column1,column2 Odoo will create a new relation table linking the two models. The table will have a name like this.
management_course_management_student_rel
However you can specify your own table name and columns for your relation table.
attendee_ids = fields.Many2many('management.student',relation='your_table_name', column1='course_id',column2='student_id', string="Attendees")
This would produce a table called your_table_name with two columns course_id and student_id
To determine what students are in a course Odoo would execute a query
SELECT student_id from your_table_name where course_id = x
And the opposite to find what courses a student is taking.

Related

Get all the rows of a table along with matching rows of another table in django ORM using select_related

I have 2 models
Model 1
class Model1(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
type = models.CharField(max_length=255)
details = models.TextField(max_length=1000)
price = models.FloatField()
Model 2
class Model2(models.Model):
id = models.IntegerField(primary_key=True)
user_id = models.ForeignKey(
User,
on_delete=models.CASCADE
)
plan_selected = models.ForeignKey(Model1)
I am trying to check whether a user has selected any plans.
The field plan_selected is a foreign key for Model1 - id. I want to get all details of Model1 along with details of Model2 in a single line of the query set using Django.
So far I have tried to get is :
sub_details = Model1.objects.select_related('Model2').filter(user_id=id)
For select_related(), you want to select on the field name, not the related model's name. But all this does is that it adds a join, pulls all rows resulting from that join, and then your python representations have this relation cached (no more queries when accessed).
You also need to use __ to traverse relationships across lookups.
Docs here: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#select-related
But you don't even need select_related() for your goal: "I am trying to check whether a user has selected any plans.". You don't need Model1 here. That would be, given a user's id user_id:
Model2.objects.filter(user_id=user_id).exists()
# OR if you have a User instance `user`:
user.model2_set.exists()
If however what you want is "all instances of Model1 related to user via a Model2":
Model1.objects.filter(model2__user_id=user_id).all()
to which you can chain prefetch_related('model2_set') (this is 1 -> Many so you're pre-fetching, not selecting - i.e fetches and caches ahead of time each results' related model2 instances in one go.)
However, that'd be easier to manage with a ManyToMany field with User on Model1, bypassing the need for Model2 entirely (which is essentially just a through table here): https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/

could not understand foreign key and manytomany field in django

I know this is a very basic question. I am learning django and i see the most important part is ForeignKey field and ManyToManyField. They are used ubiquitously. Without understanding those two, a proper model cannot be designed. If i have to design a model with FK relation, i always have to see the example first and try to come with the solution. I cannot confidently design a model cause i have not understand this well. It would be great if someone make me understand so that the picture comes to my head what is FKField, how FKField and MTMField are generated in table with simple english(Language is one of the barrier for me to understand from the documentation).
Here is the model for foreign key
class Category(models.Model):
name = models.CharField()
class Product(models.Model):
name = models.CharField()
category = models.ForeignKeyField(Category, related_name="product")
In django, you can add one instance of a "variable" as a part of a table: That is a ForeignKey.
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=30)
category = models.ForeignKey(Category)
class Category(models.Model):
name = models.CharField(max_length=30)
Here, you will have a SQL table named "[NAME OF YOUR APP]_product" that will have two columns: "name" and "category_id".
You will have an other table named "[NAME OF YOUR APP]_category" that will contain one column "name".
Django will know that when you load a Product, it will have to get its category_id, and then get that element from the category table.
This is because you use a foreignkey: it is one "variable". And it is "Many to One" because you can have many Products having the same Category.
Then you have "Many to Many". Here you can have more than one "variable"
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=30)
category = models.ManyToManyField(Category)
class Category(models.Model):
name = models.CharField(max_length=30)
Here, the difference is that you will get a table named "[NAME OF YOUR APP]_product" with only one column: "name".
Next to that, you will have a table "[NAME OF YOUR APP]_product_category", that will have the columns "product_id" and "category_id".
And one last table that will be "[NAME OF YOUR APP]_category" that will have one column: "name".
The way it works is that Django will get the Product, and see that it have a ManyToMany field of Category.
It will go to "[NAME OF YOUR APP]_product_category" and get the list of ids for the product_id you need, and get them from "[NAME OF YOUR APP]_category".
This is Many to Many because you can have a lot of Products that have each lots of different Category.
If you still don't understand, I will edit this post to add a SQL example of what the database looks like.
(Sorry, this is not really pleasant to read and a really broad way to explain how Django handle things, but I tried to do short and simple statements.)

Django ManyToMany Field

I need to make a smart menu, for which I need a ManyToMany relation.
My model is:
from django.db import models
class Health_plan(models.Model):
a = models.IntegerField ()
b = models.IntegerField ()
class Doctors_list(models.Model):
name = models.CharField(max_length=30)
hp_id = models.ManyToManyField(Health_plan)
def __unicode__(self):
return self.name
How do I make this relation in the database ? I was thinking in puting the health_plans (a,b) as columns, and the doctors as rows, with 0s and 1s to identify their covered health_plans.
Someone told me this was a misuse of a ManyToManyField, I don't know wich step to take.
Help appreciated
The approach of puting the health_plans as columns is not necessarily wrong, but it implies that you have a fixed number of health plans and that you will never add a new one.
The traditional approach for many-to-many relationships in relational databases is to introduce a table in the middle. This table will just contain the association between a doctor and a health plan.
If you have a Doctor table that contains:
id name
1 foo
2 bar
And a HealthPlan table:
id model
1 a
2 b
You then add a table Doctor_HealthPlan that is like:
doctor_id healthplan_id
1 2
2 1
2 2
The ManyToMany field type in django will automatically create this table for you. Your code is correct, but you should probably rename hp_id to something like health_plans, since it is a proxy that allows you to access the list of health plans associated to a doctor.
Django's ORM already takes care of the intermediate table so you don't have to "make this relation(ship) in the database", but given your question you obviously need to learn about proper relational model normalisation - if you don't understand the relational model you won't get nowhere with Django's ORM, nor with any other sql stuff FWIW.
For the record, in the relational model, a many to many relationship is modeled as a relation ("table" in SQL) with foreign keys on both other tables, ie:
health_plan(#health_plan_id, name, ...)
doctor(#doctor_id, firstname, lastname, ...)
doctors_health_plans(#health_plan_id, #doctor_id)
So your django models should be:
class HealthPlan(models.Model):
# no need to define an 'id' field,
# the ORM provides one by default
name = models.CharField(....)
class Doctor(models.Model):
firstname = models.CharField(....)
lastname = models.CharField(....)
health_plans = models.ManyToManyField(HealthPlan, related_name="doctors")
Then you'll be able to get all HealthPlans for a Doctor :
doc = Doctor.objects.get(pk=xxxx)
doc.health_plans.all()
and all Doctors for an HealthPlan:
plan = HealthPlan.objects.get(pk=xxxx)
plan.doctors.all()
The FineManual(tm) is your friend as usual...
You just need to save the two models first then add the healthplan instance to the doctors list. Django will handle the rest for you .
For example :
doctor_list = Doctors_list(name="Bwire")
health_plan.save()
doctor_list.save()
#Then add the plan to the doctors list.
doctor_list.hp_id.add(health_plan)
Django creates the tabels for you. In your project folder run:
python manage.py syncdb
Health_plan and Doctors_list are both tables.
'a' and 'b' are columns in Health_plan. 'Name' and 'hp_id' are columns in Doctors_list.
Django will create a column for id in each table. Django will also create a table "Doctor_list_Health_plan" to store the relation information.
Django models are Python classes, so the Python naming conventions apply. Use HealthPlan and Doctor (CapitalizeWord singular).
Your field names are a bit abstract. I suggest you use more descriptive names. Eg:
class HealthPlan(models.Model):
name = models.CharField()
extra_care = models.BooleanField()

How to specify uniqueness across a relationship in Django

I'm trying to represent some movie ratings data in Django. Here is a simplified version of my models that illustrates my problem:
class RatingSystem(models.Model):
"""This denotes a rating authority and territory in which they operate"""
name = models.CharField(max_length=16)
territory = models.CharField(max_length=32)
class Rating(models.Model):
"""This represents a rating designation used by a rating system."""
code = models.CharField(max_length=16)
description = models.TextField()
system = models.ForeignKey(RatingSystem)
class FilmRating(models.Model):
"""This is a rating for a film and the reason why it received the rating.
Each film can have many ratings, but only one per rating system.
"""
rating = models.ForeignKey(Rating)
film = models.ForeignKey('Film')
reason = models.TextField()
class Film(models.Model):
"""Data for a film."""
title = models.CharField(max_length=64)
synopsis = models.TextField()
ratings = models.ManyToManyField(Rating, through=FilmRating)
As the comments indicate, each Film can have multiple ratings, but only one rating per rating system. For instance, a film cannot be rated both 'R' and 'PG' by the MPAA. However, it can be rated 'R' by the MPAA and '15' by the BBFC.
I'm struggling to formalize this constraint in Django. I'd like to do:
unique_together = ('film', 'rating__system')
in FilmRating but following a relationship like that doesn't seem to be allowed. If I were using pure SQL, I would make code and system a composite primary key in Rating, then make a unique constraint on system, and film in FilmRatings. Unfortunately, Django does not support composite keys. I've considered overriding the save() method of FilmRating, but I'd prefer to have the constraint at the database level if possible.
Anyone have any idea how to do this? Restructuring the tables would be fine too if it would help.
EDIT: Updated answer based on #JoshSmeaton's and #MSaavedra's comments
Using Django's syncdb hook, you could run the ALTER TABLE statements directly on the database. Django will raise an IntegrityError if the unique constraint is violated, even though that constraint wasn't defined by django.
Then, adding the constraint to validate_unique would reduce developer confusion later on and safely enforce the constraint in Django.
I think you should take a look at validate_unique
This same problem some years ago in stackoverflow
The Django Docs
You can use model field validation.
https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

django model foreignkeys question

I am very new to programming and databases and I have a question about foreignkeys in django.
Say I have a model called Expenses that has a foreignkey pointed to Employees model.
class Employees(models.Model):
...
class Expenses(models.Model):
...
employee = models.ForeignKey(Employees)
I see that foreignkey field is an employee ID.
So my question is, if in practice I have an employee's name accessible to me on a form, I would have to:
get the employee id from the Employees table with the name
Insert the employee id as the foreign key into the Expenses table like this:
emp_id = Employees.object.get(name = 'John Doe')
new_expense = Expenses(foo = 'bar', ..., employee_id = emp_id.employee_id,)
new_expenses.save()
Am I doing this right? If so is this the correct way to do it?
Model class names should be singular. This will read much better in Python. You can have the associated database table have a different name by using class Meta: inside the model class. Also, the default Manager is objects, not object.
You don't need to go through all that trouble. Django will take care of mapping IDs. It creates a "reverse" field in the destination model of the ForeignKey. The name of this reverse connection is the name of the model with the ForeignKey plus _set. So, in your case, Employees will have an auto-generated field named expenses_set which acts as a manager containing all that employee's expenses. The manager has methods such as create and delete as well. So your example is just:
new_expense = (Employee.objects.get(name='John Doe')
.expense_set.create(foo='bar', ...))
Though it's better to keep tabs on the Employee object:
employee = Employee.objects.get(name='John Doe')
new_expense = employee.expense_set.create(foo='bar', ...)
(No spaces around = when used in parameter lists.) Note that you don't need to set the employee ID this way.
That said, most of us provide ForeignKey with a better name for that reverse link by using the related_name parameter:
class Expenses(models.Model):
...
employee = models.ForeignKey(Employees, related_name='expenses')
...
employee = Employee.objects.get(name='John Doe')
new_expense = employee.expenses.create(foo='bar', ...)
BTW, if you want to get the expenses for an employee, there are three ways. One is like above:
employee = Employee.objects.get(name='John Doe')
employee_expenses = employee.expenses.all()
Or the one-liner:
employee_expenses = Employee.objects.get(name='John Doe').expenses.all()
There's also:
employee_expenses = Expense.objects.filter(employee__name="John Doe")
The __ says to dereference the ForeignKey to get to its fields. The first way does two queries, the others do one, but you don't get the intermediate Employee object for use later.

Categories