How to join multiple models and get the result in pythonic way? - python

I have 4 models.
class User(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField()
class Subscription(models.Model):
user_id = models.ForeignKey(User)
title = models.CharField()
class Address(models.Model):
user_id = models.ForeignKey(User)
street = models.CharField()
class Wallet(models.Model):
user_id = models.ForeignKey(User)
balance = models.DecimalField(max_digits=6, decimal_places=2)
Here I want to get the subscription rows along with the respected user address and wallet balance. Is that possible to retrieve in a single query (ORM)?
I heard about select_related() and prefetch_related(). But not sure how to put all together in a single queryset.
How can I achieve this in pythonic way?

Have you tried to follow this snippet from documentation?
Having a User object instance you can do something like this to access subscriptions:
user.subscription_set.all()
It will require separate calls to different managers to collect all your data though.

First of all remove _id from FK fields. You'll still have subscription.user_id (int) and subscription.user which is User. Right now you have to write subscription.user_id_id for accessing id.
Do you understand that user can have multiple wallets and addresses with you db design?
It is not possible to do it in a single query with ORM. But it is possible to do it in 3 queries (doesn't matter how many records).
UPDATED:
class User(models.Model):
name = models.CharField()
class Subscription(models.Model):
user = models.ForeignKey(User, related_name='subscriptions')
title = models.CharField()
class Address(models.Model):
user = models.ForeignKey(User, related_name='addresses')
street = models.CharField()
class Wallet(models.Model):
user = models.ForeignKey(User, related_name='wallets')
balance = models.DecimalField(max_digits=6, decimal_places=2)
subscriptions = Subscription.objects.select_related('user').prefetch_related(
'user__wallets', 'user__addresses')
for s in subscriptions:
print(s.user.name)
for wallet in s.user.wallets.all():
print(wallet.balance)
for address in s.user.addresses.all():
print(address.street)

Related

Models in Python Django not working for Many to Many relationships

I am trying to create the proper Django model that could fit the following reqs:
Person Class has 1 to many relations with the Address Class
Person Class has many to many relations with the Group Class
Book Class contains the collections of the Persons and the Groups
This is my code:
class Person(models.Model):
first_name = models.CharField(max_length=15)
last_name = models.CharField(max_length=20)
def __str__(self):
return self.first_name+ ' - ' + self.last_name
class Address(models.Model):
person = models.ForeignKey(Person)
address_line = models.CharField(max_length=200)
def __str__(self):
return self.address_line
class Group(models.Model):
group_name = models.CharField(max_length=12)
persons = models.ManyToManyField(Person)
def __str__(self):
return self.group_name
class Book(models.Model):
record_name = models.CharField(max_length=12)
person = models.ForeignKey(Person )
group = models.ForeignKey(Group )
def __str__(self):
return self.record_name
However it's not correct:
1) A Group can now contain multiple Persons but the Persons do not contain any Group.
I am not sure if I should add to the Person class the following code:
groups = models.ManyToManyField(Group)
2) The Book class now contains only 1 record of Person & Group per Book record.
3) When I added the Foreign Keys to the models, I removed
on_delete tag:
person = models.ForeignKey(Person, on_delete=models.CASCADE())
because it does not compile it, asking for some params.
I know how to make all this for C#, but I am a kinda stucked with this simple task in Python/Django.
1) The ManyToMany field should appear only in one of the models, and by looks of things you probably want it in the Person model.
Its important to understand that the data about the ManyToMany field is saved in a differant table. Django only allows this field to be visable through buth models (so basiclly, choose where it is move convinient).
2)By the look of your structure I will suggest you use a ManyToMany field through a different table. here is an example:
class Activity(models.Model):
name = models.CharField(max_length=140)
description = models.TextField(blank=True, null=True)
class Route(models.Model):
title = models.CharField(max_length=140)
description = models.TextField()
activities_meta = models.ManyToManyField(Activity, through = 'RouteOrdering')
class RouteOrdering(models.Model):
route = models.ForeignKey(Route, on_delete=models.CASCADE)
activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='activita')
day = models.IntegerField()
order = models.IntegerField(default=0)
that way the data is binded to the ManyToMany field

Fetching model instance from a multiple direct relationship

Can anyone help me fetch data from this model structure? because i have a hard time doin this for hours now.
First I would like to get all distinct SubSpecialization from all Doctor which has a given Specialization.title
Secondly I would like to get all Doctor which has a specific Specialization.title and has no SubSpecialization.
Here is the Doctor model
class Doctor(models.Model):
name = models.CharField(max_length=50)
room_no = models.IntegerField()
floor_no = models.IntegerField()
contact_no = models.CharField(max_length=50, blank=True, null=True)
notes = models.CharField(max_length=70, blank=True, null=True)
This is the model Doctor relationship is connected to Specializationand SubSpecialization.
class DoctorSpecialization(models.Model):
doc = models.ForeignKey(Doctor, models.DO_NOTHING)
spec = models.ForeignKey('Specialization', models.DO_NOTHING)
class DoctorSubSpecialization(models.Model):
doc = models.ForeignKey(Doctor, models.DO_NOTHING)
sub_spec = models.ForeignKey('SubSpecialization', models.DO_NOTHING)
This is where i would make a criteria.
class Specialization(models.Model):
title = models.CharField(unique=True, max_length=45)
point = models.IntegerField()
class SubSpecialization(models.Model):
title = models.CharField(max_length=100)
There is no direct relationship between the Specialization and SubSpecialization please help.
Firstly, your specialization and subspecialization are both many-to-many relationships with Doctor. You should declare that explicitly, and drop those intervening models unless you need to store other information on them.
class Doctor(models.Model):
...
specializations = models.ManyToManyField('Specialization')
subspecializations = models.ManyToManyField('SubSpecialization')
Now you can query for all the subspecializations for doctors who have a specific specialization:
SubSpecialization.objects.filter(doctor__specialization__title='My Specialization')
Your second query doesn't make sense given the fact there is no relationship between specialization and subspecialization, you'll need to clarify what you mean by "no subspecialization in a specific specialization".
Edit
To find doctors who have a specific Specialization and then no subspecializations at all:
Doctor.objects.filter(specialization__name="My Specialization",
subspecialization=None)

Django model with a list

How to implement a list in a Django model?
Lets say I have a UserProfile model, and each user can have a list of mortgages (undefined quantity) defined by MortgageModel.
class MortgageModel(models.Model):
bank_name = models.CharField(max_length=128)
sum = models.BigIntegerField()
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# list of morgtages?
my only idea is to make a old school list, where every mortgage can point to another one or null, like this:
class MortgageModel(models.Model):
bank_name = models.CharField(max_length=128)
sum = models.BigIntegerField()
next_mortgage = MortgageModel(null=True, default=null)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mortgages = MortgageModel(null=True, default=null)
is there any other possibility?
You'll have to assign a ForeignKey to User , so that each Mortgate 'belongs' to a user.
That is how a One-To-Many relationship is done. Then, if you want to get the list of Mortgages a user have, you'd filter them out like MortgageModel.objects.filter(related_user=user)
So, you'd have something like
Model
class MortgageModel(models.Model):
bank_name = models.CharField(max_length=128)
sum = models.BigIntegerField()
related_user = models.ForeignKey(UserProfile)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
View
list_of_mortages = MortgageModel.objects.filter(related_user=user)

Django Models relations

Below is my Django models code
from django.db import models
class BookUser(models.Model):
email= models.CharField(max_length=254,primary_key=True) #mail address key
name = models.CharField(max_length=254) #max 64 char (lower case?)
contact= models.CharField(max_length=12)
imei = models.CharField(max_length=16) #imei number
address= models.TextField() #list of address ids
booksInShelf:[] #list of user book's unique ids
booksUnderCirculation:[] #list of user book's unique ids
class Meta:
ordering = ('email',)
class Book(models.Model):
isbn = models.CharField(max_length=13)
title=models.CharField(max_length=500)
description =models.TextField()
author = models.CharField(max_length=200)
userRating = models.CharField(max_length=1)
users = #list of user ids hold this book in shelf
class UserBook(models.Model):
#id: generated by django
bookId: #id of parent book
rent= models.BooleanField(default=False) #boolean is ready to rent
sell= models.BooleanField(default=False) #boolean is ready to sell
price =models.FloatField() #selling price
rentBase=models.FloatField() #base price of rent
rentPeriod=models.IntegerField() #days after which extra rent would apply
dateModified =models.DateTimeField(auto_now=True) #track date it came into shelf
dateAdded = models.DateTimeField(auto_now_add=True)
Here BookUser is the actual user who has some books in two categories i.e booksinShelf and bookUnderCirculation
class Book is central repository of all books, I need to define a one to many relation to BookUser.What is the easy way to do this?
User Book is specific to BookUser and it should be uniquely pointing to Class Book , So its many to one relation to Book Class.
I am confused on how to handle ids of UserBook and Book?
Also how to store the list of ids of UserBooks in class BookUser??
After looking at the Models and explanation provided below the Book model the users field should have ForeignKey relationship with the BookUser model.
so Book model should look like
class Book(models.Model):
isbn = models.CharField(max_length=13)
title=models.CharField(max_length=500)
description =models.TextField()
author = models.CharField(max_length=200)
userRating = models.CharField(max_length=1)
users = models.ForeignKey(BookUser, null=True, blank=True)
if you are using Postgresql and if you just need the pk list of booksInShelf and booksUnderCirculation then your BookUser model should look like
class BookUser(models.Model):
email= models.CharField(max_length=254,primary_key=True)
name = models.CharField(max_length=254)
contact= models.CharField(max_length=12)
imei = models.CharField(max_length=16)
address= models.TextField()
booksInShelf = models.ArrayField(models.IntegerField())
booksUnderCirculation = models.ArrayField(models.IntegerField())
and if you wish to have the full information of booksInShelf and booksUnderCirculation (not just the pk but other information related to the book as well), then you need to define it as ManyToMany relation.
class BookUser(models.Model):
email= models.CharField(max_length=254,primary_key=True)
name = models.CharField(max_length=254)
contact= models.CharField(max_length=12)
imei = models.CharField(max_length=16)
address= models.TextField()
booksInShelf = models.ManyToMany(UserBook)
booksUnderCirculation = models.ManyToMany(UserBook)
also rather than creating two ManyToMany fields in the BookUser model you can have two flags in your UserBook model called is_in_shelf and is_under_circulation. These fields would be BooleanField, you can check more about the model fields in Django Documentation here: https://docs.djangoproject.com/en/1.10/topics/db/models/#fields
This should do what you want :
class UserBook(models.Model):
bookId = models.ForeignKey('Book')
Here a UserBook has a reference to a Book item, and severals users can have the same book, but it's still a unique reference in you table Book.
Hope it helps

Django Foreign key query

I have the following modle
class PatientContact(models.Model):
uid = models.CharField(max_length=10)
name = models.CharField(max_length=100)
phone = PhoneNumberField()
class Patient(models.Model):
name = models.CharField(max_length=100)
date_of_birth = models.DateField()
contact = models.ForeignKey(PatientContact)
class Appointment(models.Model):
patient = models.ForeignKey(Patient)
time = models.DateTimeField()
I can get the list of patients registered under a user:
Patient.objects.filter(contact=uid)
How could I get the list of appointment for a user from the above model?
Used case:
The list of appointments scheduled by user (uid=1234)
Not sure how to perform a backward relationship to get list of appointments for a given uid.
If I understood you correctly, this isn't backward, it's just two levels deep:
Appointment.objects.filter(patient__contact__uid=1234)

Categories