Unclear of type of relationship to use - jpa-2.0

I have two tables, person and country.
Country is a table with all the countries, e.g. "Singapore", "America". While person is a table with all the users, storing their names, and country of residence etc.
The database table looks like this:
person
person_id int PK
name varchar(20)
country_id int FK
country
country_id int PK
country varchar(20)
I am trying to come up with a class diagram that looks like this: However, i am unclear of what relationship should i indicate for the variable Country inside of the Person class.
#Entity
#Table(name=person)
class Person{
#Id
#Column(name="person_id")
#GeneratedValue(strategy=GeneratedType.IDENTITY)
private int personId;
#Column(name="name")
private String name;
# ?
private Country country;
// Accessor and Mutator
}
#Entity
#Table(name=country)
private Country{
#Id
#Column(name=country_id)
#GeneratedValue(strategy=GeneratedType.IDENTITY)
private int countryId;
#Column(name="country")
private String country;
// Accessor and Mutator
}

Person should contain the foreign key of Country.
This creates the relationship that a Person belongs to one (residential) country, while a country can have (of course) more Persons belonging to it. This is called a many-to-one relationship (if viewed from Country).

Related

Django query objects using non related models

I have these 3 models:
class Person(models.Model):
name
age
class Person_Address(models.Model):
address
number
city
state
person = models.ForeignKey(Person)
class State_Schedules(models.Model):
state
hour
I also have a models.QuerySet for the State_Schedules for filtering based on current time (basically the contactables() below).
How can I get the Person objects comparing it's state in django?
I tried this but it seems cumbersome having to fetch the Persons using their Person_Address.
persons = Person_Address.objects.select_related('person').filter(
state__in=(
_.state for _ in State_Schedules.objects.contactables()
)
)
If I could access the Person_Address association as a keyword to the Person's filter, this should be pretty easy, but I haven't found how to do so.
Is there a better approach or I'd have to resort to raw sql?
There is a foreign key from Person_Address to Person, so you can filter on the reverse relationship. Use double underscore notation to filter on fields in the Person_Address model.
states = [_.state for _ in State_Schedules.objects.contactables()]
people = Person.objects.filter(person_address__state__in=states)

Django - Optimize queries with select_related()

I have the following model.
class Car(models.Model):
owner = models.ForeignKey('Driver')
class Country(models.Model)
name = models.CharField(max_length=255)
class Driver(models.Model):
name = models.CharField(max_length=255)
age = models.IntegerField()
country = models.ForeignKey('Country')
I want to select the name of drivers owning a car.
Car.objects.all().values('owner__name')
Do I need to use select_related() method, to avoid a join for each object, or it is redundant because implicit with values() method?
Car.objects.all().select_related('owner').values('owner__name')
In the same way, I want, this time, the name of countries with drivers owning a car. Which one is the best?
Car.objects.all().values('owner__country__name')
Car.objects.all().select_related('owner', 'country').values('owner__country__name')
Car.objects.all().select_related('owner__country').values('owner__country__name')
First, all the occurrences of .all() in your examples can be deleted; the manager (.objects) already has almost all methods of the QuerySet, except for .delete().
.select_related is only helpful when your eventual query returns model instances; then, all the foreign key of each instance will be pre-loaded.
But if you are using .values you are getting dictionaries, and there are no foreign key attributes to pre-load. So it should not be used in that case.
When you do .values('owner__name') Django already sees that it needs to join owners and cars, no extra queries are done.
In the last one you want Countries, so use Country.objects:
Country.objects.filter(driver__car__isnull=False).values('name')

how to display many2many relationship data in odoo

First Table
class vehicle_service(models.Model):
s_type=fields.Many2many('service.service','service_rel','sid','s_type',string="Service Name", required="1")
Second Table
class service_service(models.Model):
_name="service.service"
name=fields.Char("Name")
cost=fields.Float("Service Cost")

Grouping by multiple columns in Django

I have a model with a few columns:
Model (id, country, city, name, age)
I need to group and sort by a few columns:
SELECT * FROM Model
WHERE country = 'USA'
GROUP BY id, city, age
ORDER BY id, city, age
and I'd like to query the same with Django ORM.
Model.objects.filter(country='USA').group_by('id', 'city', 'age').order_by('id', 'city', 'age')
But this call throws after group_by as it returns None.

Django select related in raw request

How to make "manual" select_related imitation to avoid undesirable DB hits?
we have:
class Country:
name = CharField()
class City:
country = models.ForeignKey(Country)
name = models.CharField()
cities = City.objects.raw("select * from city inner join country on city.country_id = country.id where name = 'london'")
#this will hill hit DB
print cities[0].country.name
How to tell django that related models are already fetched.
A solution with prefetch_related (this means that two queries will be made, 1 for the cities and 1 for the countries) taken from django-users which is not part of the public API but is working on Django 1.7
from django.db.models.query import prefetch_related_objects
#raw querysets do not have len()
#thats why we need to evaluate them to list
cities = list(City.objects.raw("select * from city inner join country on city.country_id = country.id where name = 'london'"))
prefetch_related_objects(cities, ['country'])
UPDATE
Now in Django 1.10 prefetch_related_objects is part of the public API.
Not sure if you still need this, but I solved it starting with Alasdair's answer. You want to use the info from the query to build the model or it'll still fire additional queries when you try to access the foreign key field. So in your case, you'd want:
cities = list(City.objects.raw("""
SELECT
city.*, country.name as countryName
FROM
cities INNER JOIN country ON city.country_id = country.id
WHERE
city.name = 'LONDON"""))
for city in cities:
city.country = Country(name=city.countryName)
The line that assigns the country doesn't hit the database, it's just creating a model. Then after that, when you access city.country it won't fire another database query.
I'm not sure if you can do this. As an alternative, you can select individual fields from the country table and access them on each instance.
cities = City.objects.raw("select city.*, name as country_name from city inner join country on city.country_id = country.id where name = 'london'")
city = cities[0]
# this will not hit the database again
city.country_name