Django Models relations - python

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

Related

Same column pointing to 2 different foreign keys in Django

I have 3 models in Django:
Student
Teacher
Publication
A single publication can have multiple authors, who can be both students and teachers. Since a student and teacher can have multiple publications and a publication can have multiple teachers and students as authors, I am using a M2M relationship using a through table called PublicationAuthor. However, I am not sure how to get my authors column in my through table. My effort so far :
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=50)
publication = models.ManyToManyField(Publication, through=PublicationAuthor, related_name='students')
class Teacher(models.Model):
name = models.CharField(max_length=50)
publication = models.ManyToManyField(Publication, through=PublicationAuthor, related_name='students')
class Publication(models.Model):
title = models.CharField(max_length=50)
class PublicationAuthor(models.Model):
publication = models.ForeignKey(Publication, on_delete=models.CASCADE)
authors =
You can do this:
class Publication(models.Model):
title = models.CharField(max_length=50)
student_authors = models.ManyToManyField(Student, related_name='student_authros')
teacher_authors = models.ManyToManyField(Teacher, related_name='teacher_authors')
So that if the publication has no author of some type the field simply remains empty.

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

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)

Restricting single Rating on each Book by each User : Django ORM

Edited Title : Limit multiple "Many to One" fields into "One to One" association : Django
We've Book, User and Rating as Django model.
Each Book has many Ratings
Each Rating has one Book
Each User has many Ratings
Each Rating has one User
For Book
class Book(models.Model):
isbn = models.CharField(max_length=32)
title = models.CharField(max_length=256)
def __str__(self):
return self.title
For Book Rating
class BookRating(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.SmallIntegerField(choices=[(i, i) for i in range(1, 6)])
def __str__(self):
return self.rating
Problem Statement
How can I ensure that each User has atmost one rating on each book?
Just do
class BookRating(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.SmallIntegerField(choices=[(i, i) for i in range(1, 6)], default=1)
class meta:
unique_together = ('book','user')
Your models do implement a many to many relationship, however you are not getting full access to the django ManyToMany functionality. I recommend you do something like this:
class Book(models.Model):
isbn = models.CharField(max_length=32)
title = models.CharField(max_length=256)
ratings = models.ManyToManyField(User,through='BookRating')
When you do this your BookRating can remain unchanged, but the small change to the Book model gives you full access to the api described here: https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/
What's interesting is that modifying the Book model as described above does not make any changes to your table structures in your database. They remain unchanged. It's simply a matter of unlocking the api.

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)

Categories