Django : Count, Group By and Order By with many to many fied - django

I have two models :
class Actors(models.Model):
name = models.CharField(max_length=128)
...
class Movies(models.Model)
title = models.CharField(max_length=128)
casting = models.ManyToManyField("actors.Actors", related_name="casting")
...
I am looking for ordering actors by using the number of movies they played in.
Django autogenerated a table with actors_id and movies_id, named movies_movies_casting :
+-----+-----------+-----------+
| id | movies_id | actors_id |
+-----+-----------+-----------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 3 | 1 |
...
Here actor #1 played in movies #1, #2 and #3. And actor #2 played only in movie #1.
Here is the request used in MySQL to get what I want :
SELECT actors_id, COUNT(movies_id) as count FROM movies_movies_casting GROUP BY actors_id ORDER BY count;
The result is :
+-----------+-------+
| actors_id | count |
+-----------+-------+
| 15 | 29 | // actor #15 played in 29 movies
| 12 | 21 |
| 24 | 17 |
| 3 | 16 |
| 20 | 15 |
| 21 | 14 |
...
What is the request used in Django to get this result ?

Try this,
from django.db.models import Count
Movies.objects.values('casting'
).annotate(
count=Count('id')).order_by('-count')

Related

Django Query "not in" M2M

I got these three models:
class Crcheck(models.Model):
crlist = models.ForeignKey("crlists.Crlist", on_delete=models.CASCADE)
persons = models.ForeignKey("persons.Person", on_delete=models.CASCADE)
...
| id | crlist_id | persons_id |
| 41 | 2 | 64 |
| 42 | 3 | 64 |
class Cuslistprofile(models.Model):
customer= models.ForeignKey("customers.Customer",on_delete=models.CASCADE)
crlist = models.ManyToManyField("crlists.Crlist")
...
class Crlist(models.Model):
dbname=models.CharField(max_length=200)
...
As a result of the M2M Django generates this table "cuslistprofiles_cuslistprofile_crlist":
| id | cuslistprofile_id | crlist_id |
| 9 | 4 | 2 |
| 13 | 4 | 3 |
| 14 | 4 | 5 |
| 19 | 4 | 7 |
I want to get all the crlist values that are in "cuslistprofiles_cuslistprofile_crlist" but missing in "crcheck". In this particular example I want to retrieve 5 and 7.
How can I achieve that in Django ORM?
You can .filter(…) [Django-doc] with:
Crlist.objects.filter(cuslistprofile__isnull=False, crcheck=None).distinct()
One can use double underscores (__) to look "through" relations.

Aggregate Sum on Django2

I have 2 tables. Table A is
+--+------------------+
| ID | Fastivalname |
+--+------------------+
| 1 | 2020Xmas |
+--+------------------+
| 2 | 2019Xmas |
+--+------------------+
| 3 | 2020Thanksgiving |
+--+------------------+
| 4 | 2019Thanksgiving |
+--+—————————+
Fastival isForeignKey for table B,and table B is
+--+------------------+ ------------------+------------------+
| ID | fastival_name_id | money | useofmoney |
+--+------------------+ ------------------+------------------+
| 1 | 1 | 100 | game
+--+------------------+ ------------------+------------------+
| 2 | 1 | 20 | clothes
+--+------------------+ ------------------+------------------+
| 3 | 3 | 50 | food
+--+------------------+ ------------------+------------------+
| 4 | 4 | 10 | game
+--+------------------+ ------------------+—————————+
| 1 | 2 | 30 | food
+--+------------------+ ------------------+------------------+
| 2 | 3 | 15 | game
+--+------------------+ ------------------+—————————+
and models.py is:
class TableA(models.Model):
Fastivalname = models.CharField(max_length=50)
class TableB(models.Model):
fastival_name = models.ForeignKey(to=TableA, related_name="TableA_Fastival_name", on_delete=models.CASCADE)
money = models.IntegerField(default=0)
useofmoney = models.CharField(max_length=200, null=True, blank=True)
Please someone tell me how to get the "sum of money in game of 2020xxx" in Django2?
I tried context["money"] = TableB.objects.filter(fastival_id=TableA.objects.filter(Fastivalname__startswith=2020.values('id')[0]['id']).filter(useofmoney="game").aggregate(Sum('money'))['money']. But that response "None"...
You can do this with a single query on TableB and use the double-underscore syntax to perform joins/filters on related models/tables
TableB.objects.filter(
fastival__Fastival__startswith='2020',
useofmoney='game'
).aggregate(total=Sum('money'))['total']

How to access generated table fields in Django manytomanyfield

py which looks like below
class Scenes(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Tech(models.Model):
tech = models.CharField(max_length=30)
scenario = models.ManyToManyField('Scenes')
def __str__(self):
return self.tech
class UserLog(models.Model):
tech_id = models.ForeignKey(Tech, on_delete=models.CASCADE)
....#other fields
It generates one extra table called pages_tech_scenario (pages is my app name)
My populated tables in database (postgres) looks like below
pages_tech_scenario
id | tech_id | scenes_id
----+---------+-----------
1 | 1 | 1
4 | 2 | 1
5 | 2 | 2
6 | 2 | 3
7 | 2 | 4
8 | 2 | 5
9 | 3 | 3
10 | 4 | 1
11 | 4 | 2
12 | 4 | 3
pages_scenes
id | name
----+----------
1 | poweron
2 | poweroff
3 | sleep
4 | wakeup
5 | switch
pages_tech
id | tech
----+------
2 | CDMA
3 | GSM
4 | 5G
1 | LTE
pages_userlog
id | data_location | pc | username | target | data_type | description | status | submission_time | upload_now | string_submission_time | tech_id_id
----+------------------------------------------------------+---------+----------+--------+-----------+-------------+-------------+-----------------------+------------+------------------------+------------
39 | C:\My Files\testFolder | lab0128 | ananagra | SDX55 | crash | | In Progress | 2020_02_12_T_17_45_04 | f | | 2
19 | C:\My Files\testFolder | lab0034 | sujaraj | SDX55 | crash | | In Progress | 2020_02_12_T_15_46_59 | f | 111 | 1
Here, for pages_userlog first entry id=39 has tech_id_id is 2 which is equivalent to CDMA. While entering the form, I had selected one of the scenario (say sleep) field of CDMA (as CDMA points to all 5 scenarios, can be seen from pages_tech_scenario table).
How can I retrieve only sleep scenario from CDMA instead of all the scenarios its pointing to?.
How to get the id from pages_tech_scenario by specifying tech_id and scenes_id?.
You can name the field from UserLog:
tech = models.ForeignKey(Tech, on_delete=models.CASCADE)
This way you can reference the id by tech_id instead of tech_id_id
How can I retrieve only sleep scenario from CDMA instead of all the
scenarios its pointing to?.
UserLog.objects.get(pk=1).tech.scenario.get(name="sleep")
How to get the id from pages_tech_scenario by specifying tech_id and
scenes_id?.
Tech.scenario.through.objects.get(tech_id=tech_id, scenes_id=scenes_id).id

Power BI - Parent Child Visualization

I would like to perform following visualization.
Following is the table.
+---------------+-------------+---------------+-------------+--------+-------------+-----------+--+
| Customer Name | Customer ID | Location Name | Location ID | Rating | Parent Name | Parent ID | |
+---------------+-------------+---------------+-------------+--------+-------------+-----------+--+
| Customer 1 | 10 | Location 1 | L1 | 23 | Null | Null | |
| Customer 1 | 10 | Location 2 | L2 | 43 | Null | Null | |
| Customer 2 | 20 | Location 21 | L3 | 42 | Customer 1 | 10 | |
| Customer 2 | 20 | Location 22 | L4 | 54 | Customer 1 | 10 | |
| Customer 3 | 30 | Location 31 | L5 | 65 | Customer 1 | 10 | |
+---------------+-------------+---------------+-------------+--------+-------------+-----------+--+
Output should include Location Name and Rating.
+---------------+--------+--+
| Location Name | Rating | |
+---------------+--------+--+
| Location 1 | 23 | |
| Location 2 | 43 | |
+---------------+--------+--+
It has 2 filter Customer Name and Include Child Customer. Include Child Customer has 2 options "Yes" and "No".
If user selects "Yes" option then report should include locations of child customer.
As I am new to Power BI, I am not sure how to model data or achieve this functionality.
Sorry for all formatting issues.
Thanks.

How to write a Django query where coloum_value < 100?

I have a table like this in DJango?
| id | user_id | name | source | remaining | start_date | time_remaining | size |
+----+---------+---------------+----------------+-----------+----------------------------+----------------+------+
| 1 | 1 | ok.txt | ngs.pradhi.com | 20 | February 05, 2013, 08:01AM | 1 | 4 MB |
| 2 | 1 | NC_008253.fna | ngs.pradhi.com | 20 | February 05, 2013, 08:02AM | 1 | 4 MB |
| 3 | 1 | test.data | ngs.pradhi.com | 0 | February 05, 2013, 08:21AM | 1 | 4 MB
I want to retrieve the data where user_id = request.user.id and remaining < 100.
Tried using:
Queue.objects.filter(user_id=request.user.id, remaining < 100) But didn't work.
Queue.objects.filter(user_id=request.user.id, remaining__lt=100).exclude(remaining=0)
Django Field lookups