I am new to Django and I want to build a Website to track boardgames.
What I want: For each round played a Player will get points and I want to create a table which shows the sum of all Scores for each Player.
My model is as follows:
class Player(models.Model):
name = models.CharField(max_length=150)
class Score(models.Model):
player = models.ForeignKey(Player, blank=False, null=False, on_delete=models.PROTECT)
scorevalue = models.IntegerField(blank=False, null=False)
I would like to get a queryset with all players where an additional field with the sum of his scores is added. In SQL something like
Select distinct playername, sum(scorevalue) over (partition by playername)
from Players
Join Scores
My main problem is to understand the connection between "aggregate" and "annotate" functions in combination with instances and querysets.
With an instance I can get
Player.objects.get(pk=1).score_set.aggregate(score_sum=Sum('scorevalue'))
but is it possible to do this for every instance in a queryset?
Thanks for the help.
Yes, in that case you annotate the objects, so with:
from django.db.models import Sum
Player.objects.annotate(
score_sum=Sum('score__scorevalue')
)
The Player objects that arise from this queryset will have an extra attribute .score_sum which is the sum of the related Score records.
One can make use of two consecutive underscores (__) to look "through" relations, and thus access data of related model records.
Related
I have a Django database model that has some attributes, one of them is a Charfield 'category' with Choices.
I now want to annotate a queryset of this model with the count of the rows of each category. The thing is, the way i know to do it, only categories present in the queryset are getting counted, but i want a queryset with all categories annotated with the count (0 if no rows with this category).
This is what im doing at the moment:
Model.objects.all().values('category').annotate(total=Count('category'))
Is there a way to display all categories, including such with count 0?
You can not count categories that do not exist, since, well... these do not exist. The choices are not even transferred to the database.
Using a CharField with choices is not the ideal modeling for this. Typically it is better to make a model Category and then another MyModel with ForeignKey [Django-doc] to link a MyModel object to a Category, so:
class Category(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class MyModel(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
then we can create categories like:
Category.objects.bulk_create(
Category(name='technology'),
Category(name='art'),
Category(name='science')
)
if we then link MyModel objects to these Categorys, we can annotate the Category with the number of MyModels with:
from django.db.models import Count
Category.objects.annotate(
num_mymodel=Count('mymodel')
)
Here the Categorys that arise from this queryset will have an extra attribute .num_mymodel with the number of linked MyModel objects. Since a LEFT OUTER JOIN is performed, for Categorys without any MyModels, it will use 0.
Apology if this is a duplicate but I could not find any satisfying answer for this case. Maybe I am doing something fundamentally wrong, like need to define models in a different way.I am also very new to django.So suggestions will be really helpful.
Suppose I have my models like this:
from django.contrib.auth.models import Group
class Team(Group):
description = models.CharField(max_length=30)
class Players(models.Model):
name = models.CharField(max_length=60)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
Now if I for example, want a queryset of all players by the Team model what can I do?
I have the foreign key in the Players model and not in Team model. So something like Team.objects.filter(logic) is needed to get all players. But exactly what logic will work here?
Any help will be much appreciated.
Django ORM also can filter by relation. these kind of filtering is valid for all kind of relations.
players = Players.objects.filter(team__id = 1)
in case you have the team object.
players = Players.objects.filter(team = team)
Django allows you get access to related objects in reverse way. It calling reverse relation. And related manager objects using for it. You can find more details here and here. In your specifc case you can get players using players_set team's attribute:
team = Team.objects.get(pk=1)
players = team.players_set.all()
Assuming I have two models:
from django.db import models
class Parent(models.Model):
pass
class Child(models.Model):
parent = models.ForeignKey(Parent,
on_delete=models.CASCADE,
related_name='children')
active = models.BooleanField()
How might I go about getting a query set of parents that have at least 1 active child? In other words, how would I get a query set of parents that excludes those without any active children? If using model properties in filters was feasible, this would be a trivial task, but that is not possible. This is also a simple operation using list comprehensions, but it's important here for the queryset to be the end result.
One solution is to use aggregation: https://docs.djangoproject.com/en/2.1/topics/db/aggregation/
We can annotate a queryset of parents with the number of active children they have, and then filter against that queryset to only find parents with a number greater than or equal to 0:
from django.db.models import Count, Q
num_active_children = Count('children', filter=Q(children__active=True))
parents_with_any_active_children = (Parent.objects
.annotate(num_active_children=num_active_children)
.filter(num_active_children__gte=1)
)
Parent.objects.filter(child__active=True)
Hope this is enough for you.
I have a situation where I need to be able to add multiple copies of the same object to a many-to-many relationship.
Let's say that the problem is recording the types of furniture someone has. Here are my base models:
class Person(models.Model):
name = models.CharField(max_length=100)
class Furniture(models.Model):
furniture_name = models.CharField(max_length=100) #e.g. Chair, Sofa.
Lets say I want to record that Sam owns 3 chairs and 2 sofas. But I don't want to make more than one sofa object in the DB. How can I do this with a many-to-many relationship? The traditional many-to-many has a unique-constraint that prevents this.
I'm thinking of using a through table, with another field in the unique-constraint (date-purchased, or just a random string). Will that work?
Does anyone have a better way of doing this?
Creating a through table is a good approach here, as everything will be DRY and pretty easy to use:
class Ownership:
owner = models.ForeignKey(Person, on_delete=models.CASCADE)
furniture = models.ForeignKey(Furniture, on_delete=models.CASCADE)
items_owned = models.IntegerField(default=0)
class Meta:
unique_together = [
'owner', 'furniture'
]
person = Person.objects.get(name='Bob')
furniture = Furniture.objects.get(furniture_name='Sofa')
# update the number of items owned
Ownership.objects.update_or_create(
owner=person, furniture=furniture, defaults=dict(items_owned=3))
# get the number of items owned
person.ownership_set.get(furniture=furniture).items_owned
# or for example
Ownership.objects.get(owner__name='Bob', furniture__name='Sofa').items_owned
You can then abstract away this complex querying and updating logic with custom managers https://docs.djangoproject.com/en/2.0/topics/db/managers/#custom-managers
Why do we use an intermediate model?
Can't we just use Many to many relationship without intermediate model?
M2M relationships require intermediate tables. You can read more about what M2M relationships are and why they require an intermediate table (referred to as a junction table in the article) here:
Django abstracts this away by automagically creating this intermediate table for you, unless you need to add custom fields on it. If you do, then you can define it by overriding the through parameter as shown here
Here's a quick picture of why the table is required
Source: https://www.geeksforgeeks.org/intermediate-fields-in-django-python/
Let's say you have two models which have a Many-to-Many relationship, like Customer and Product. One customer can buy many products and a product can be bought by many customers.
But you can have some data that doesn't belong to neither of them, but are important to the transaction, like: quantity or date.
Quantity and date are the intermediary data which are stored in intermediary models.
from django.db import models
class Item(models.Model):
name = models.CharField(max_length = 128)
price = models.DecimalField(max_digits = 5, decimal_places = 2)
def __str__(self):
return self.name
class Customer(models.Model):
name = models.CharField(max_length = 128)
age = models.IntegerField()
items_purchased = models.ManyToManyField(Item, through = 'Purchase')
def __str__(self):
return self.name
class Purchase(models.Model):
item = models.ForeignKey(Item, on_delete = models.CASCADE)
customer = models.ForeignKey(Customer, on_delete = models.CASCADE)
date_purchased = models.DateField()
quantity_purchased = models.IntegerField()
When you buy a product, you do it through the Purchase model: the client customer buys quantity_purchased quantity of items item in date_purchased.
The Purchase model is the Intermediate model.
Django documentation says:
...if you want to manually specify the intermediary table, you can use
the through option to specify the Django model that represents the
intermediate table that you want to use.
In this case we have this line in the Customer model, which defines the intermediary model in through = 'Purchase'
items_purchased = models.ManyToManyField(Item, through = 'Purchase')
Let's now use the example from the Django Documentation.
You have a database of musicians with a Many-to-Many relationship with the bands the belong to: a musician can belong can be part of many bands, and the bands can have many musicians.
What data do you want to keep?
For musicians (person): name and instrument they play
For the bands: name and style.
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
age = models.IntegerField()
class Group(models.Model):
name = models.CharField(max_length=128)
style = models.CharField(max_length=128)
person = models.ForeignKey(Person, on_delete=models.CASCADE)
But, wouldn't you think that knowing when the person joined the band is important? What model would be the natural place to add a date_joined field? It makes no sense to add it to Person or Group, because it's not an intrinsic field for each of them, but it's related to an action: joining the band.
So you make a small, but important adjustment. You create an intermediate model that will relate the Person, the Group with the Membership status (which includes the date_joined).
The new version is like this:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
age = models.IntegerField()
class Group(models.Model):
name = models.CharField(max_length=128)
style = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
The changes are:
You added a new class called Membership which reflects the membership status.
In the Group model you added members = models.ManyToManyField(Person, through='Membership'). With this you relate Person and Group with Membership, thanks to through.
Something important to clarify.
An intermediate model, or in relational database terms, an associative entity, are always needed in a Many-to-Many (M2M) relationship.
A relational database requires the implementation of a base relation
(or base table) to resolve many-to-many relationships. A base relation
representing this kind of entity is called, informally, an associative
table... that can contain references to columns from the same or different database tables within the same database.
An associative (or junction) table maps two or more tables together by
referencing the primary keys of each data table. In effect, it
contains a number of foreign keys, each in a many-to-one relationship
from the junction table to the individual data tables. The PK of the
associative table is typically composed of the FK columns themselves. (source)
Django will create the intermediate model, even when you don't explicitly define it with through.
Behind the scenes, Django creates an intermediary join table to
represent the many-to-many relationship. By default, this table name
is generated using the name of the many-to-many field and the name of
the table for the model that contains it.
Django will automatically generate a table to manage many-to-many
relationships. However, if you want to manually specify the
intermediary table, you can use the through option to specify the
Django model that represents the intermediate table that you want to
use.
The most common use for this option is when you want to associate extra data with a many-to-many relationship.(source)