The below is a database of colleges, and its ratings. The below is how I thought
Each Class (Batch, ex: Batch of 2009) belongs to a Department
Each Department (ex: department of pharmacy) belongs to a College
As I am particularly concerned about Ratings. I thought to Rate a Batch, there by using a Manager or some Model Method, I can calculate Total Department or College Ratings.
Each Class has Ratings
Note: There may be many ratings by different Users for a single Class. So, I guess Total or Average ratings should be done by a Method!
This is how I so far did
class Rating(models.Model):
positive = models.FloatField(default=0)
negative = models.FloatField(default=0)
class College(models.Model):
name = models.CharField(max_length=200)
website = models.URLField()
class Department(models.Model):
name = models.CharField(max_length=200)
college = models.ForeignKey(College)
class Batch(models.Model):
passout_year = models.IntegerField(max_length=4)
department = models.ForeignKey(Department)
rating = models.ForeignKey(Rating)
This schema has some issues!
Each Batch can only have single rating! However, I am looking for multiple ratings signed by many Users (Though Users model is not integrated yet)
Each Batch belongs to a Department, Each Department belongs to a College. However, we can also think of the relationships in another way
Each College has many Departments, Each Department has many Batches While.. Each Batch has Many Departments (ex: there may be many departments in 2009), and Each Department can be in Many colleges
So, should I use ManyToManyField instead of ForeignKey?
How should I schema should look like?
One of the most essential changes I think are
class Rating(models.Model):
..
..
user = models.ForeignKey(django.contrib.auth.models.User)
class College(models.Model):
..
..
departments = models.ManyToManyField(Department)
class Department(models.Model):
..
college = models.ForeignKey(College)
batches = models.ManyToManyField(Batch)
class Batch(models.Model):
..
department = models.ForeignKey(Department)
rating = models.ManyToMany(Rating)
Is this going to be right? How should it look if if not
Thanks
Here it goes:
from django.contrib.auth.models import User#First import user
lass Rating(models.Model):
..
..
user = models.ForeignKey(User)
class College(models.Model):
..
..
departments = models.ManyToManyField(Department)
class Department(models.Model):
..
college = models.ForeignKey(College)
batches = models.ManyToManyField(Batch)
class Batch(models.Model):
..
department = models.ForeignKey(Department)
rating = models.ManyToMany(Rating)
When you make many to many relationship a bridge entity is automatically created by Django.
Related
Suppose that you want to simulate universities system, you have courses, teachers and students.
We have some courses that are taught by some teachers and students choose some courses with some teachers.
For example:
Courses: math, physics
Teachers: Jack(math), Jane(math, physics)
Students: st1(math with Jack), st2(math with Jane), st3(physics with Jane and cant choose Jack!!), every score by default=-1.
With this code:
teachers = models.ManyToManyField(teacher.objects.filter(t_courses=s_courses), verbose_name='Ostad')
I got errors like:
raise AppRegistryNotReady("Models aren't loaded yet.") and
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
from django.db import models
class profile(models.Model):
n_id = models.IntegerField(primary_key=True, verbose_name='code melli')
name = models.CharField(max_length=24, verbose_name='Full Name')
class Meta:
ordering = ('name',)
class course(models.Model):
name = models.CharField(max_length=24, verbose_name='Class Name')
unit = models.SmallIntegerField()
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class teacher(profile,models.Model):
t_id = models.AutoField(primary_key=True)
t_courses = models.ManyToManyField(course, verbose_name='Dars')
def __str__(self):
return self.name
class student(profile,models.Model):
s_id = models.AutoField(primary_key=True)
s_courses = models.ManyToManyField(course, verbose_name='Dars')
#teachers = ??????????????????????????
score = models.IntegerField(default=-1, verbose_name='Nomre')
def __str__(self):
return self.name
How do I code in the teachers part?
Thanks a lot.
You're trying to do two different things here: Define which teacher gives a course for each specific student and restrict the choices (which is more a validation thing).
You're missing the actual Class model which links the course to the teacher and that you can use to define which classes the student is following:
class Teacher(models.Model):
name = models.CharField(max_length=100)
courses = models.ManyToManyField(Course, through="Class", related_name="teachers")
class Class(models.Model):
teacher = models.ForeignKey(Teacher, related_name="classes")
course = models.ForeignKey(Course, related_name="classes")
class Student(models.Model):
classes = models.ManyToManyField(Class)
The Class model is now your intermediate model for linking teachers to courses. You could also add more information about the class, such as its number, schedule (e.g. list of weekdays and hours the class takes place) and room number. Now you can fetch all the other things like that:
# all courses a teacher teaches
teacher.courses.all()
# all teachers of a student
[class.teacher for class in student.classes.all()] # list
Teacher.objects.filter(classes__in=student.classes.all()) # QuerySet
# all courses of a student
Course.objects.filter(classes__in=student.classes.all())
Now because you associate the student with the a Class instance, you can't select a wrong teacher. If for example you have a form where the user can pick a course, you'd present the classes belonging to that course in order to link the student to a course/teacher combination:
# teachers for a course
course.teachers.all()
If you want to keep track of the marks of the students for each class, you can add a Mark model as an intermediate model for your m2m relationship:
class Mark(models.Model):
student = models.ForeignKey(Student, related_name='marks' ...)
class = models.ForeignKey(Class, ...)
grade = models.DecimalField(max_digits=3, decimal_places=1, default=-1)
class Student(models.Model):
classes = models.ManyToManyField(Class, through='Mark', related_name='students')
But probably a more suitable model is to keep track of all the marks, e.g. when there are many exams for one class and you want to keep track of all the results. Then you just keep the Mark model above but don't use it as intermediate model to classes. In that way a student can have multiple grades for the same class:
student = Student.objects.get(id=1)
student.marks.filter(class__name='math').aggregate(Avg('grade'))
>> {'grade__avg': Decimal('8.3')}
I'm trying to figure out how to model the an election in Django. I have a model Candidate. There have to be exactly two candidates, so the definition is as follows:
class Candidate(models.Model):
name = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
def __str__(self):
return self.name + ' ' + self.surname
def clean(self):
if (len(Candidate.objects.all()) > 1):
raise ValidationError(
"There are two candidates already"
)
And I want to have a model CountyResult, with the following fields: county (foreign), number of residents, number of residents eligible for voting etc. and with the final results of the election in this county.
I would like to be able to insert the election results in the admin site.
And my question is: how can I implement the Candidate -> votes mapping inside the CountyResult model? I was thinking about simply storing values first_candidate_votes, second_candidate_votes, but that's obviously not a great solution, since I would like to be able to remove a candidate.
I was also thinking about adding a SingleResult model with a foreign key candidate and somehow 'put it' inside the CountyResult class, but there is no such thing as a two-to-one relation in Django
I would appreciate any hints. I'm new to Django, so it's almost certain that the solution is rather easy and technical
If I understand you correctly, it makes most sense to me to have 3 models: Candidate, County, and Results. County would have the county, residents, and eligible voters fields. Results will have foreign keys to Candidate and County and then the vote count field (either total or two fields if you want to keep the vote tally separate).
class Candidate(models.Model):
name = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
class County(models.Model):
name = models.CharField(max_length=50)
population = models.IntegerField(max_length=50)
eligible_voters = models.IntegerField(max_length=50)
class Result(models.Model):
name = models.CharField(max_length=50) # you could give an election a name I suppose, i.e. 2016 primary
county = models.ForeignKey('County',)
winner = models.ForeignKey('Candidate',)
loser = models.ForeignKey('Candidate',)
total_votes = models.IntegerField(max_length=50) # break this out into other fields if you want more detail
im doing some models and have a thought while designing them, here is an example: a bank buys stock shares, so one bank can have many stock shares and many stock shares can be bought from many banks, its a many to many relationship but when a bank buys a stock shares it has to keep a record of the price and the date/period/round of the purchase, works the same for a sale, o in order to keep record of all of that im doing a class something like this:
class Bank(models.Model):
name = models.Charfield()
money = models.IntegerField()
class StockShares(models.Model):
name = models.Charfield()
price = models.Charfield()
now to make a relationship i know i have to add
stock = models.ManyToManyField(StockShares)
but then how do i add the relationship attributes that only exist when a purchase or sale happens?
i was thinking maybe i can do something like this:
class Bank(models.Model):
name = models.Charfield()
money = models.IntegerField()
class StockShares(models.Model):
name = models.Charfield()
price = models.Charfield()
class Sale(models.Model):
bank = models.ForeignKey(Bank)
stockshares = models.ForeignKey(StockShares)
date = models.DateField()
quantity = models.ForeignKey()##this should be the quantity of stockshares sold in $ im just lazy to write it down
this is what i would to normaly without using django and inside a database manager
is there a way to aproach to this in django without doing an intermediate class to deal with the relationship? or im doing my thougth good and this is how things have to be done in django
pd: english is not my first language im doing my best here
thanks in advance for answering!
You are looking for an Extra fields on many-to-many relationships
Your code should look like this:
class Bank(models.Model):
name = models.Charfield()
money = models.IntegerField()
members = models.ManyToManyField(StockShares, through='Sale')
class StockShares(models.Model):
name = models.Charfield()
price = models.Charfield()
class Sale(models.Model):
bank = models.ForeignKey(Bank)
stockshares = models.ForeignKey(StockShares)
date = models.DateField()
Maybe quantity should be calculated field
Hi i'm not very good at English but i'll try to explain myself the best i could. I'm using python and Django to create a web project.
I have this 4 models (this is the best translation i can do of the tables and fields):
class Humans (models.Model):
name = models.CharField(max_length=15)
surname = models.CharField(max_length=15)
doc_num = models.CharField(max_length=11)
...
class Records (models.Model):
closing_state = models.CharField(max_length=2)
...
humans = models.ManyToManyField(Humans, through='Reco_Huma')
class Reco_Huma (models.Model):
id_record = models.ForeignKey(Records)
id_human = models.ForeignKey(Humans)
categorys = models.CharField(max_length=2)
reserv_identity = models.CharField(max_length=2)
repre_entity = models.CharField(max_length=2)
class Observations (models.Model):
id_record = models.ForeignKey(Records)
text = models.CharField(max_length=80)
category = models.CharField(max_length=2, choices=CAT)
Now given a doc_num from Humans, a text from Observations i want to get a QuerySet Of all the Records.
To clarify i first do this:
q1 = Reco_Huma.objects.filter(id_human.doc_num=x)
q2 = Observations.objects.filter(text=y)
both query-sets give me a list of id_record and then i want to connive that lists and filter the Records table with that id_record's
I hope you can understand me
Thanks in advance
To rephrase your query, you want all the Records associated with a certain Human and which have a certain Observation. So it should be:
result = Records.objects.filter(observations__text=y, humans__doc_num=x)
As a general rule, if you want to end up with a certain type of object, it helps to start from there in your query.
I'm having a hard time trying to figure out how to use annotations in the Django ORM to achieve grouping through a model.
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=255)
class Store(models.Model):
name = models.CharField(max_length=255)
class Order(models.Model):
customer = models.ForeignKey(Customer)
store = models.ForeignKey(Store)
order_date = models.DateTimeField()
If my Stores are Los Angeles, Denver, Houston & Atlanta, how do I get a count of
Customers by store using the latest order date?
Los Angeles: 25
Denver: 210
Houston: 400
Atlanta: 6
Define a ManyToMany field on either Customer or Store, pointing to the other model, with Order as the through table. For example:
class Store(models.Model):
name = models.CharField(max_length=255)
orders = models.ManyToManyField(Customer, through=Order)
Now you can do:
from django.db.models import Count
Store.objects.annotate(Count("orders__customer"))