Modelling results of an election in Django - python

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

Related

Django form list field or json field?

I have a model called participants as below
class participants(models.Model):
username= models.CharField(max_length =50)
votes = models.IntegerField(default=0)
voted_by = ?
Votes is the total number of votes given by users and single user can vote multiple times. If the user have voted then the user should wait 1 hour to vote again. Now i am wondering, how can i store users id in a way that it would be easier to know who voted how many times and the recent date and time the user have voted.
Can someone suggest me or refer some examples that i can solve this problem.
You can create another model (eg. VotesHistory)...
class VotesHistory(models.Model):
class Meta:
verbose_name = "Vote Log"
verbose_name_plural = "Vote Logs"
time = models.DateTimeField(auto_now=True, verbose_name="Time")
uid = models.IntegerField(verbose_name="Voter's UserID")
pid = models.IntegerField(verbose_name="Voted UserID")
Now, when user 1 will vote user 2, you can create an entry such as,
VotesHistory(uid=user1.id, pid=user2.id).save()
This kind of problem is generally solved by using a ForeignKey reference.
# class name should begin with a capital letter and should be singular for a model
class Participant(models.Model):
username = models.CharField(max_length =50)
class Vote(models.Model)
vote_to = models.ForeignKey(Participant, on_delete=models.CASCADE, related_name='vote_to')
voted_by = models.ForeignKey(Participant, on_delete=models.CASCADE, related_name='voted_by')
date_time = models.DateTimeField(auto_now=True)
Each vote by a participant would be a row in the Votes table or an object of type Vote.
Something like,
vote = Vote(vote_to=some_participant_object,
voted_by=someother_participant_object)
vote.save()
auto_now=True means the value will be added when the object gets created so you don't have to handle when the vote was cast.
You can then query the number of votes cast by a particular participant using the ORM.
A basic filter query should be enough. Get all the votes by a particular participant.
Something like,
# just as an idea here, the next lines might not be perfect
votes = Vote.objects.filter(voted_by__id=some_participant_id)
# or
votes = Vote.objects.filter(voted_by=some_participant_object)
# check the timestamp of the last vote and build logic accordingly
This way it'll be easier to write ORM queries to count the number of votes a particular participant has or the number of votes a particular participant has cast.

Query to fetch highest rated movie with mimimum 5 people rated

I want to fetch name of movie with maximum rated movie with minimum 5 people rated in django.
My code :
model.py
class Movie(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
vote_count = models.IntegerField()
class Watchlist(models.Model):
userid = models.IntegerField()
movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE)
rating = models.IntegerField()
what will be query to get movie with highest rating with minimum 5 people ?
I propose that you make some changes to your model. Normally ForeignKeys do not end with an id suffix, since Django will add a "twin field" with an _id suffix that stores the value of the target field. Furthermore you probably better make a ForeignKey to the user model. If you do not specify a primary key yourself, Django will automatically add an field named id that is an AutoField, hendce there is no need to add that manually. Finally you do not need to store the vote_count in a field of the Movie, you can retrieve that by counting the number of related Rating objects:
from django.conf import settings
class Movie(models.Model):
title = models.CharField(max_length=100)
class Rating(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete.models.CASCADE)
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
rating = models.IntegerField()
Then we can retrieve the highest rated movie with:
from django.db.models import Avg, Count
higest_rated = Movie.objects.annotate(
rating=Avg('rating__rating'),
votes=Count('rating')
).filter(votes__gte=5).order_by('-rating').first()
Here the votes__gte=5 will filter such that it will only obtain Movies with five or more votes, and we order by rating in descending order.
I'd modify the model, moving out Rating entity related fields from Watchlist and Movie.
Add the "Rate" class, and then filter by two conditions:
Count(Rate for the exact Movie) > minimum threshold(e.g. 5)
AVG(rating score for the exact Movie) > minimum threshold(e.g. 5)
or, if you need top-rated movies, use Order by as it described in that answer
In your case, you could use Count and Average with Watchlist.Rating field

Linking one models with a set of another in Django

I am currently working on developing a database and API system where users can create a portfolio which contains a list of coins. I am using Django and I searched everywhere but I kept seeing foreign keys but I'm not sure that's what I need in this situation.
I want two models, one for portfolios which a user will be able to query on, and another coin model which the user will be able to also query on. However in the portfolio there should be a list of coins. I know how to do this in Java using objects but not sure the method in Django.
Here is my model class:
from django.db import models
class Portfolio(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return self.name
class Coin(models.Model):
name = models.CharField(max_length=100)
symbol = models.CharField(max_length=5)
price = models.DecimalField(max_digits=20, decimal_places=9)
info = models.TextField()
website = models.TextField()
rank = models.IntegerField()
def __str__(self):
return self.name + " - " + self.symbol
Now I would ideally have something like coins = list of Coins model if I was using java to make the objects, but since this is for a database and in Django I'm not sure how I should link the two.
I've seen related objects but did not understand the explanations for my issue. How should I go about setting up these models? Thanks.
It sounds like you want to have a number of Portfolio objects each of which can have varying investments in Coin objects. In this case, you'd want to use a ManyToManyField:
class Portfolio(models.Model):
name = models.CharField(max_length=250)
coins = models.ManyToManyField(Coin)
The database would then store the two dimensional table of which Portfolio holds which coin.
However an alternate approach you could try is to create an object that separately represents the investment:
class Investment(models.Model):
portfolio = models.ForeignKey(Portfolio)
coin = models.ForeignKey(Coin)
bought = models.DateTimeField() # date the investment was made
sold = models.DateTimeField() # date the investment was sold
amount = models.DecimalField() # number of coins held
You could then add a property to Portfolio:
class Portfolio(models.Model):
name = models.CharField(max_length=250)
#property
def coins(self):
return Investment.objects.filter(portfolio=self)
In this way you can not only keep track of which portfolio holds which coins, buy also the entire historical positions too.

When to use ManyToOne and ManyToMany relationships

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.

Filtering a QuerySet With another QuerySet

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.

Categories