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'))
Related
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 have to 2 entity models
class User(ndb.Model):
username = ndb.StringProperty()
# other properties
class Item(ndb.Model):
type = ndb.StringProperty()
# other properties
with a many to many relationship between User and Item
class UserItem(ndb.Model):
user = ndb.KeyProperty(kind=User)
item = ndb.KeyProperty(kind=Item)
# other properties
How can I query UserItem with a filter to Item.type. Something like select * from UserItem where UserItem.user = user_key and UserItem.item.type = item_type.
I know I can do it with StructuredProperty but there is an entity limit of 1mb. If it's not possible with the model how should I model the relationship to get get the query with filter work in datastore?
Thanks
You can't do this, and you shouldn't try. The datastore is not a relational database, and shouldn't be used as one.
Rather than having a linking UserItem table, you should consider storing a list of keys in one of the entities. For example, you could add a field to User:
items = ndb.KeyProperty(kind=Item, repeated=True)
and then with your User object, get the items by key and filter out the ones you need:
user_items = ndb.get_multi(my_user.items)
relevant_items = [item for item in user_items if item.type == my_type]
The exact structure is going to depend on your use-case, but the point is not to think in terms of traditional relationships like you would in SQL.
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()
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.
Hi I am trying to build an application which has models resembling something like the below ones:-(While it would be easy to merge the two models into one and use them , but that is not feasible in the actual app)
class User(db.Model):
username=db.StringProperty()
email=db.StringProperty()
class UserLikes(db.Model):
username=db.StringProperty()
food=db.StringProperty()
The objective- The user after logging in enters the food that he likes and the app in turn returns all the other users who like that food.
Now suppose a user Alice enters that she likes "Pizzas" , it gets stored in the datastore. She logs out and logs in again.At this point we query the datastore for the food that she likes and then query again for all users who like that food. This as you see are two datastore queries which is not the best way. I am sure there would definitely be a better way to do this. Can someone please help.
[Update:-Or can something like this be done that I change the second model such that usernames become a multivalued property in which all the users that like that food can be stored.. however I am a little unclear here]
[Edit:-Hi Thanks for replying but I found both the solutions below a bit of a overkill here. I tried doing it like below.Request you to have a look at this and kindly advice. I maintained the same two tables,however changed them like below:-
class User(db.Model):
username=db.StringProperty()
email=db.StringProperty()
class UserLikes(db.Model):
username=db.ListProperty(basestring)
food=db.StringProperty()
Now when 2 users update same food they like, it gets stored like
'pizza' ----> 'Alice','Bob'
And my db query to retrieve data becomes quite easy here
query=db.Query(UserLikes).filter('username =','Alice').get()
which I can then iterate over as something like
for elem in query.username:
print elem
Now if there are two foods like below:-
'pizza' ----> 'Alice','Bob'
'bacon'----->'Alice','Fred'
I use the same query as above , and iterate over the queries and then the usernames.
I am quite new to this , to realize that this just might be wrong. Please Suggest!
Beside the relation model you have, you could handle this in two other ways depending on your exact use case. You have a good idea in your update, use a ListProperty. Check out Brett Slatkin's taslk on Relation Indexes for some background.
You could use a child entity (Relation Index) on user that contains a list of foods:
class UserLikes(db.Model):
food = db.StringListProperty()
Then when you are creating a UserLikes instance, you will define the user it relates to as the parent:
likes = UserLikes(parent=user)
That lets you query for other users who like a particular food nicely:
like_apples_keys = UserLikes.all(keys_only=True).filter(food='apples')
user_keys = [key.parent() for key in like_apples_keys]
users_who_like_apples = db.get(user_keys)
However, what may suit your application better, would be to make the Relation a child of a food:
class WhoLikes(db.Model):
users = db.StringListProperty()
Set the key_name to the name of the food when creating the like:
food_i_like = WhoLikes(key_name='apples')
Now, to get all users who like apples:
apple_lover_key_names = WhoLikes.get_by_key_name('apples')
apple_lovers = UserModel.get_by_key_names(apple_lover_key_names.users)
To get all users who like the same stuff as a user:
same_likes = WhoLikes.all().filter('users', current_user_key_name)
like_the_same_keys = set()
for keys in same_likes:
like_the_same_keys.union(keys.users)
same_like_users = UserModel.get_by_key_names(like_the_same_keys)
If you will have lots of likes, or lots users with the same likes, you will need to make some adjustments to the process. You won't be able to fetch 1,000s of users.
Food and User relation is a so called Many-to-Many relationship tipically handled with a Join table; in this case a db.Model that links User and Food.
Something like this:
class User(db.Model):
name = db.StringProperty()
def get_food_I_like(self):
return (entity.name for entity in self.foods)
class Food(db.Model):
name = db.StringProperty()
def get_users_who_like_me(self):
return (entity.name for entity in self.users)
class UserFood(db.Model):
user= db.ReferenceProperty(User, collection_name='foods')
food = db.ReferenceProperty(Food, collection_name='users')
For a given User's entity you could retrieve preferred food with:
userXXX.get_food_I_like()
For a given Food's entity, you could retrieve users that like that food with:
foodYYY.get_users_who_like_me()
There's also another approach to handle many to many relationship storing a list of keys inside a db.ListProperty().
class Food(db.Model):
name = db.StringProperty()
class User(db.Model):
name = db.StringProperty()
food = db.ListProperty(db.Key)
Remember that ListProperty is limited to 5.000 keys or again, you can't add useful properties that would fit perfectly in the join table (ex: a number of stars representing how much a User likes a Food).