django model foreignkeys question - python

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.

Related

Django: join two table on foreign key to third table?

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.

Many2many relation in Odoo 10 (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.

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()

SQLAlchemy ORM Insertion based on related object

This is kind of a newbie question. I am new to ORM and I would like to know if the following is possible:
Let's say I have a "users" table with three fields: "id", "user_name", and a foreign key "country_id" that points to the table "countries"
Now, if I want to insert a new user, I first look for the id of the country in "countries" table (for instance 11) and then I create an instance of User (declarative base object)
new_user = User('Johnny', 11)
session.add(new_user)
What I would like to know, if it is possible to add directly the new user, passing only the country name... something like this:
new_user = User('Johnny', Country('Spain')) # Note the country instance
session.add(new_user)
I tried things like this, but the best result I got is that the ORM tries to insert another country called Spain.
Thanks in advance!!
Assuming that Spain has already been inserted in the database, you'll need the following:
new_user = User(name='Johnny', country_id=session.query(Country).filter_by(name='Spain').one().id)
which in a clearer version is:
country = session.query(Country).filter_by(name='Spain').one()
new_user = User(name='Johnny', country_id=country.id)
if you have a User.country relationship defined this can simply be:
country = session.query(Country).filter_by(name='Spain').one()
new_user = User(name='Johnny', country=country)
if the User.country relationship has a users backref relationship defined (which will be mapped by default to a list), you can also do:
country = session.query(Country).filter_by(name='Spain').one()
country.users.add(User(name='Johnny'))

Getting the first item item in a many-to-many relation in Django

I have two models in Django linked together by ManyToMany relation like this:
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person)
I need to get the main person in the group which is the first person in the group. How can I get the first person?
Here's how I'm adding members:
grp = Group.objects.create(name="Group 1")
grp.save()
prs = Person.objects.create(name="Tom")
grp.members.add(prs) #This is the main person of the group.
prs = Person.objects.create(name="Dick")
grp.members.add(prs)
prs = Person.objects.create(name="Harry")
grp.members.add(prs)
I don't think I need any additional columns as the id of the table group_members is a running sequence right.
If I try to fetch the main member of the group through Group.objects.get(id=1).members[0] then Django says that the manager is not indexable.
If I try this Group.objects.get(id=1).members.all().order_by('id')[0], I get the member with the lowest id in the Person table.
How can I solve this?
Thanks
Django doesn't pay attention to the order of the calls to add. The implicit table Django has for the relationship is something like the following if it was a Django model:
class GroupMembers(models.Model):
group = models.ForeignKey(Group)
person = models.ForeignKey(Person)
Obviously, there's nothing there about an "order" or which you should come first. By default, it will probably do as you describe and return the lowest pk, but that's just because it has nothing else to go off of.
If you want to enforce an order, you'll have to use a through table. Basically, instead of letting Django create that implicit model, you create it yourself. Then, you'll add a field like order to dictate the order:
class GroupMembers(models.Model):
class Meta:
ordering = ['order']
group = models.ForeignKey(Group)
person = models.ForeignKey(Person)
order = models.PositiveIntegerField(default=0)
Then, you tell Django to use this model for the relationship, instead:
class GroupMembers(models.Model):
group = models.ForeignKey(Group)
person = models.ForeignKey(Person, through='GroupMembers')
Now, when you add your members, you can't use add anymore, because additional information is need to complete the relationship. Instead, you must use the through model:
prs = Person.objects.create(name="Tom")
GroupMembers.objects.create(person=prs, group=grp, order=1)
prs = Person.objects.create(name="Dick")
GroupMembers.objects.create(person=prs, group=grp, order=2)
prs = Person.objects.create(name="Harry")
GroupMembers.objects.create(person=prs, group=grp, order=3)
Then, just use:
Group.objects.get(id=1).members.all()[0]
Alternatively, you could simply add a BooleanField to specify which is the main user:
class GroupMembers(models.Model):
group = models.ForeignKey(Group)
person = models.ForeignKey(Person)
is_main_user = models.BooleanField(default=False)
Then, add "Tom" like:
prs = Person.objects.create(name="Tom")
GroupMembers.objects.create(person=prs, group=grp, is_main_user=True)
And finally, retrieve "Tom" via:
Group.objects.get(id=1).members.filter(is_main_user=True)[0]
Relational database don't have any notion of ordering, by default. There's no such thing as "first". You need to add an explicit "order" field which keeps the order, and order by it.
You were pretty close:
Group.objects.get(id=1).members.all()[0]
(But as Alex Gaynor says in his answer, for predictable behaviour you need a proper field to sort on)
to reliably keep a record of who is the "main" person in a group, you may want to have a look at using a through table to keep this metadata

Categories