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()
Related
I have three models
class A(Model):
...
class B(Model):
id = IntegerField()
a = ForeignKey(A)
class C(Model):
id = IntegerField()
a = ForeignKey(A)
I want get the pairs of (B.id, C.id), for which B.a==C.a. How do I make that join using the django orm?
Django allows you to reverse the lookup in much the same way that you can use do a forward lookup using __:
It works backwards, too. To refer to a “reverse” relationship, just use the lowercase name of the model.
This example retrieves all Blog objects which have at least one Entry whose headline contains 'Lennon':
Blog.objects.filter(entry__headline__contains='Lennon')
I think you can do something like this, with #Daniel Roseman's caveat about the type of result set that you will get back.
ids = B.objects.prefetch_related('a', 'a__c').values_list('id', 'a__c__id')
The prefetch related will help with performance in older versions of django if memory serves.
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.
I am creating a web application to manage robotics teams for our area. In the application I have a django model that looks like this:
class TeamFormNote(models.Model):
team = models.ForeignKey(Team, blank=True, null=True)
member = models.ForeignKey(TeamMember, blank=True, null=True)
notes = models.TextField()
def __unicode__(self):
if self.team:
return "Team Form Record: " + unicode(self.team)
if self.member:
return "Member Form Record: " + unicode(self.member)
Essentially, I want it to have a relationship with team or a relationship with member, but not both. Is there a way to enforce this?
I can only see two viable solutions. First is actually the same as #mariodev suggested in the comment which is to use Genetic foreign key. That will look something like:
# make sure to change the app name
ALLOWED_RELATIONSHIPS = models.Q(app_label = 'app_name', model = 'team') | models.Q(app_label = 'app_name', model = 'teammember')
class TeamFormNote(models.Model):
content_type = models.ForeignKey(ContentType, limit_choices_to=ALLOWED_RELATIONSHIPS)
relation_id = models.PositiveIntegerField()
relation = generic.GenericForeignKey('content_type', 'relation_id')
What that does is it sets up a generic foreign key which will allow you to link to any other model within your project. Since it can link to any other model, to restrict it to only the models you need, I use the limit_choices_to parameter of the ForeignKey. This will solve your problem since there is only one generic foreign key hence there is no way multiple relationships will be created. The disadvantage is that you cannot easily apply joins to generic foreign keys so you will not be able to do things like:
Team.objects.filter(teamformnote_set__notes__contains='foo')
The second approach is to leave the model as it and manually go into the database backend and add a db constaint. For example in postgres:
ALTER TABLE foo ADD CONSTRAINT bar CHECK ...;
This will work however it will not be transparent to your code.
This sounds like a malformed object model under the hood...
How about an abstract class which defines all common elements and two dreived classes, one for team and one for member?
If you are running into trouble with this because you want to have both referenced in the same table, you can use Generic Relations.
I have about 5 tables with user foreign key, i.e.:
class Passport(models.Model):
user = models.OneToOneField(User)
...
Also, classes like UserProfile, Company, UserOptions, NotifySettings, etc. I need to get dict with joined values for user-summary page. Also i need to join to this union this summary stats:
rent_sums = WriteOff.objects.filter(created_at__range=(rent_start, rent_finish), write_off_type='rent').values('user').\
annotate(rent_amount=Sum('amount')).order_by()
How can i do it without manualy update of a result dict?
you can do this by executing a custom SQL from django but the main problem I see here is the way the models are been handled, it would be a lot easier if you mixed all this user foreign keys to be in the UserProfile, for example:
class UserProfile(models.Model):
user = fields.OneToOneField(User)
company = fields.ForeignKey(Company)
options = fields.ForeignKey(Options)
notification_settings = fields.ForeignKey(NotifySettings)
...
This way you can use the ORM django brings with more ease. In my opinion it would be faster for you to create a migration instead of this huge query.
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.