Django count distinct number of related model - django

Consider the following models:
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
publisher = models.ForeignKey(Publisher, related_name='related_books')
From a Publisher instance how can I get the number of book by distinct value on pages field? For example:
| name | pages | publisher |
|-----------|-------|-----------|
| Golden | 20 | 1 |
| Grey | 23 | 1 |
| Blue | 20 | 1 |
| Grotesque | 27 | 2 |
If I have publisher = Publisher.objects.get(id=1) how can I achieve something like this:
# equals to 2 [Golden, Grey]
publisher.related_books.all().distinct('pages').count()

You were close, you just need to restrict returned values, like so:
publisher.related_books.all().values('pages').distinct('pages').count()
This will just give you the number of different page lengths for a publisher, but not the associated books for each page length. To do that you'd probably need an extra query.

If you want reusable queries, you could do this:
class BookQuerySet(models.QuerySet):
def by_publisher(self, publisher):
return self.filter(publisher=publisher)
def distinct_number_of_pages(self):
return self.distinct(pages)
class Book(...):
...
objects = BookQuerySet.as_manager()
class Publisher(...):
#property
def number_of_page_lengths(self):
return Book.objects.by_publisher(self).distinct_number_of_pages().count()

Related

How to get count of subjects taken by each student?

I've two models 'Students' and 'Enrollments'.
The schema for these is as below:
class Students(models.Model):
id = models.AutoField(primary_key=True, unique=True)
name = models.CharField()
class Enrollments(models.Model):
enroll_id = models.AutoField(primary_key=True, unique=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
subjects = models.charField()
I'm trying to achieve the result of following SQL query in Django Rest Framework, for getting number of subjects enrolled by students (individually).
select
s.id, s.name, count(e.subjects) as count
from Students as s
left outer join Enrollments as e
on e.student_id_id = s.id
group by s.id, s.name, e.subjects
order by count asc;
This query returns result like:
---------------------------
| id | name | count |
---------------------------
| 1 | a | 1 |
| 2 | b | 0 |
| 3 | c | 2 |
---------------------------
Can anyone please help me acheive this kind of result.
Note: I need 0 count students details also.
What you can do is when you are creating a serializer, you can add a serializer method field which will get the count for you.
Add this at the top of your serializer:
count = serializers.SerializerMethodField('get_count')
Then add a function inside your serializer like this:
def get_count(self, obj):
try:
return Enrollments.objects.filter(student_id=obj.id).count()
except:
return None
Finally, add 'count' to your field list. You can then add as many fields as you want. I hope this will get you your desired result. Also don't forget to use "select_related" in the ORM inside your view to reduce the amount of queries.

Get latest payment from related model in Django Admin

I'd like to output a table using "Premises" model in Django admin. In addition I'd like include the output in this table of an additional column, say "last utility payment". It is actually a column in a related table. There may be no payment in the database so admin should able to see either an empty cell or the date of payment.
I was able to write a DB query that displays the information I need. Its significant and worked part is given below:
SELECT jp.id,
jp.number apartment,
jp.building_number building,
jp.rent,
jp.arrears,
jpm.last_payment
FROM jasmin_premises jp
LEFT JOIN (
SELECT pm.premises_id,
max(pm.paid) last_payment
FROM jasmin_payment pm
GROUP BY pm.premises_id
) jpm ON jp.id = jpm.premises_id;
And the output is similar to the following:
id | apartment | building | rent | arrears | last_payment
--------------------------------------------------------------
170 | 1X | 6-A | 297.43 | 2.57, | NULL
72 | 2 | 4 | 289.66 | -678.38 | 2021-01-31
173 | 3Z | 7 | 432.86 | 515.72 | 2021-02-04
73 | 4 | 8-B | 292.25 | 515.44 | 2021-02-04
74 | 5 | 8-B | 112.42 | 3249.34 | NULL
75 | 6A | 122 | 328.48 | 386.23 | 2021-02-04
76 | 7 | 42 | 482.06 | 964.12 | 2021-01-31
77 | 8 | 1 | 433.71 | 867.42 | 2021-01-31
78 | 9C | 12 | 322.79 | 322.79 | 2021-02-04
79 | 10 | 122 | 324.22 | 0 | 2021-02-04
80 | 12 | 12 | 322.79 | 1232.46 | NULL
81 | 14 | 5-Z | 440.82 | 978.44 | 2021-02-04
And I'm using the following models (only a significant part):
class Premises(models.Model):
number = models.CharField(
blank=False,
null=False,
max_length=10)
building_number = models.CharField(
blank=False,
null=False,
max_length=3)
rent = models.DecimalField(
blank=False,
null=False,
max_digits=12,
decimal_places=2,
default=0.0)
area = models.DecimalField(
blank=False,
null=False,
max_digits=5,
decimal_places=2)
class Payment(models.Model):
paid = models.DateField(
blank=False,
null=False)
premises = models.ForeignKey(
Premises,
blank=False,
null=False,
on_delete=models.CASCADE,
related_name='payments',
db_index=True)
Is there a way to override admin.ModelAdmin.get_queryset (for example using annotations) to get an extra column like in my example above? Is there any other way to make a LEFT JOIN on a compound DB query using Django ORM?
to make this query in django you have to add the models.Manager() to the tables like this:
models.py
class Premises(models.Model):
# existent code
objects = models.Manager()
class Payment(models.Model):
# existent code
objects = models.Manager()
In the part of app you want to access this information
from .models import Premises, Payment
premises = Premises.objects.all()
data_to_display = []
for premise in premises:
payments = Payment.objects.filter(premises=premise).order_by('-paid')
if len(payments) == 0:
last_payment = "Null"
else:
last_payment = payments[0]
object_to_list = {
"id": premise.id,
"apartment": premise.number,
"building": premise.building_number,
"rent": premise.rent,
"arreaars": premise.area,
"last_payment": last_payment.paid
}
data_to_display.append(object_to_list)
The solution is to add an explicit subquery to a QuerySet using the Subquery expression. We'll need also to use OuterRef because a queryset in a Subquery needs to refer to a field from the outer query.
So let's create a subquery:
from django.db.models import OuterRef
payments = Payment.objects.filter(
premises=OuterRef('pk')
).order_by('-paid')
The next step is to pass payments subquery to a queryset:
from django.db.models import Subquery
# 'payments' here is from example above
premises = Premises.objects.annotate(
last_payment=Subquery(payments.values('paid')[:1])
)
Finally, lets see the used SQL to query objects rows the database:
print(premises.query)
(the output is formatted, only the significant part is shown)
SELECT "jasmin_premises"."id",
"jasmin_premises"."number",
"jasmin_premises"."building_number",
"jasmin_premises"."arrears",
"jasmin_premises"."rent",
(SELECT U0."paid"
FROM "jasmin_payment" U0
WHERE U0."premises_id" = "jasmin_premises"."id"
ORDER BY U0."paid" DESC
LIMIT 1) AS "last_payment"
FROM "jasmin_premises";
Now, after performing the tests, we can use this in our ModelAdmin:
from django.contrib import admin
from django.db.models import OuterRef, Subquery
from .models import Payment, Premises
#admin.register(Premises)
class PremisesAdmin(admin.ModelAdmin):
list_display = (
'number',
'building_number',
'rent',
'arrears',
'last_payment',
)
def get_queryset(self, request):
qs = super().get_queryset(request)
payments = Payment.objects.filter(
premises=OuterRef('pk')
).order_by('-paid')
qs = qs.annotate(
last_payment=Subquery(payments.values('paid')[:1]),
)
return qs
def last_payment(self, obj):
return obj.last_payment
last_payment.short_description = 'Last payment'
last_payment.admin_order_field = 'last_payment'
Well, this doesn't use JOINs, but this approach will force Django to execute a subquery.
Probably in some cases it may be possible to write an equivalent queryset that performs the same task more clearly or efficiently however, this is the best I have achieved so far.

Django reading data from 2 models with foreignkey and make single list

I'm new to django. I've been coding with sql but django orm is hard for me to convert my knowledge of sql to orm models.
I've client model
class client(models.Model):
c_id = models.AutoField(primary_key=True)
name= models.TextField()
age=models.IntegerField()
and address model
class address(models.Model):
c_id = models.ForeignKey(client, on_delete=models.CASCADE)
addr = models.CharField(max_lenght=20)
city= models.CharField(max_lenght=20)
This is my table
---------------------------
| c_id|Name | age |
---------------------------
| 1 | John | 23 |
----------------------------
| 2 | Rose | 20 |
----------------------------
------------------------------
| c_id|addr | city |
------------------------------
| 1 | buspark | florida|
------------------------------
| 2 | homesquare| florida|
------------------------------
how to get allclient with address in list
Look at values() docs
The values() method takes optional positional arguments, *fields,
which specify field names to which the SELECT should be limited. If
you specify the fields, each dictionary will contain only the field
keys/values for the fields you specify. If you don’t specify the
fields, each dictionary will contain a key and value for every field
in the database table.
__ allows get related data, so in your case it could look like this
address.objects.values('c_id__c_id', 'c_id__name', 'c_id__age', 'addr', 'city')

Define blueprints grouping objects in Django

Django modelling question:
I'm writing a manufacturing e-commerce site. We have an inventory of all components and we want to define blueprints for products that we could build using those components. How could I model that?
Say for example I have a class AtomicComponent
class AtomicComponent(models.Model):
component = models.CharField(max_length=255)
length = models.IntegerField(blank=True, null=True)
thickness = models.IntegerField(blank=True, null=True)
colour = component = models.CharField(max_length=255)
quantity = models.IntegerField(blank=True, null=True)
+----+------------+--------+-----------+--------+----------+
| id | Component | length | thickness | colour | quantity |
+----+------------+--------+-----------+--------+----------+
| 45 | table-legs | 80 | 3 | white | 90 |
| 46 | table-tops | 100 | 3 | white | 25 |
| 47 | bolts | 1 | null | null | 3000 |
+----+------------+--------+-----------+--------+----------+
How could I specify blueprints like:
ikea-table: 4x(id=45) + 1x(id=46) + 4x(id=47)
Trying to find a way so that the product could have a relationship with specific objects so that when a customer tries to order a table, it would check if all the components are available.
You should create another model to store each component of the blueprint:
class Blueprint(models.Model):
name = models.CharField(max_length=250)
atomic_component = models.ForeignField(AtomicComponent, on_delete=models.PROTECT, related_name='components')
amount = models.PositiveIntegerField(default=1)
This model with store a record for every component in the blueprint, with the amount of them on field ´amount´.

How to query most recent record across multiple tables in django

I have two models that look like this:
class Node(models.Model):
user = models.ForeignKey(User, null=False)
name = models.CharField(max_length=50)
class Activation(models.Model):
node = models.ForeignKey(Node, null=False)
active = models.BooleanField(default=False)
datetime = models.DateTimeField(default=datetimeM.datetime.now)
The activation table stores whether a given node is "active" or not. So to figure out whether a node is active, one needs to get the latest activation record for that node.
I'm trying to figure out how to write a django query that returns all active nodes.
Here is some example data
Node Table
id | name
--------------------
0 | andrew
1 | bill
2 | bob
Activation Table
id | nodeId | active | datetime
--------------------
0 | 0 | false | 01-01-2013:00:01:02
1 | 0 | true | 01-02-2013:00:01:02
2 | 0 | false | 01-03-2013:00:01:02
3 | 1 | false | 01-04-2013:00:01:02
4 | 0 | true | 01-05-2013:00:01:02
5 | 1 | true | 01-06-2013:00:01:02
6 | 2 | false | 01-07-2013:00:01:02
So the query would need to return [node0, node1]
class Node(models.Model):
user = models.ForeignKey(User, null=False)
name = models.CharField(max_length=50)
class Activation(models.Model):
node = models.ForeignKey(Node, null=False, related_name='activations')
active = models.BooleanField(default=False)
datetime = models.DateTimeField(default=datetimeM.datetime.now)
#latest activation record for that node:
try:
latest_activation = node.activations.latest('id')
except:
latest_activation = None
# Return all active notes:
all_active_notes = Node.objects.filter(activations__active=True)
Updated:
Check this question what I posted yestarday:
Django reverse query by the last created object
maybe this will help you.