Django ORM IF statement - django

I have this table
With SQL query i can get aggregated information about total "amount" for avery car, and amount of "checked"|"uncheked" rows and sign of finished checking for all rows for one car:
SELECT
car_id
, SUM(amount) as total_amount
, Sum(IF(checked=1,1,0)) as already_checked
, Sum(IF(checked=0,1,0)) as not_cjecked
, IF(Sum(IF(checked=0,1,0))=0,1,0) as check_finished
FROM
refuels_flow
GROUP BY car_id
Result:
+--------+--------------+-----------------+-------------+----------------+
| car_id | total_amount | already_checked | not_cjecked | check_finished |
+--------+--------------+-----------------+-------------+----------------+
| 1 | 1300 | 1 | 12 | 0 |
| 2 | 300 | 3 | 0 | 1 |
+--------+--------------+-----------------+-------------+----------------+
The question is - how i can do this with Django ORM (without use of raw query)?

To obtains the same SQL output, you may use the following queryset:
already_checked = Sum(Func('checked', function='IF', template='%(function)s(%(expressions)s=0, 0, 1)'))
not_checked = Sum(Func('checked', function='IF', template='%(function)s(%(expressions)s=0, 1, 0)'))
check_finished = Func(
not_checked,
function='IF', template='%(function)s(%(expressions)s=0, 1, 0)'
)
Refuels.objects.values('car_id').annotate(
total_amount=Sum('amount'),
already_checked=already_checked,
not_checked=not_checked,
check_finished=check_finished
)
Check the doc on expressions for more informations.
Now, already_checked could be simplified with:
already_checked = Sum('checked')
And instead of having the not_checked and check_finished annotations, you could annotate the count and easily compute them in Python, for example:
qs = Refuels.objects.values('car_id').annotate(
count_for_car=Count('car_id'),
total_amount=Sum('amount'),
already_checked=Sum('checked'),
)
for entry in qs:
not_checked = entry['count_for_car'] - entry['already_checked']
check_finished = not_checked == 0

Related

Django one column values to one column concat value using annotate Subquery returns more than 1 row

hellow my models see the blow
class IP(models.Model):
subnet = models.ForeignKey(Subnet,verbose_name="SUBNET",on_delete=models.CASCADE,related_name="ip_set")
ip = models.GenericIPAddressField(verbose_name="IP",protocol="both",unpack_ipv4=True,unique=True)
asset = models.ManyToManyField(Asset,verbose_name="HOSTNAME",through="AssetIP",related_name="ip_set",blank=True,)
description = models.CharField(verbose_name="DESCRIPTION",max_length=50,default="",null=True,blank=True)
class AssetIP(models.Model):
TYPE_CHOICES = [
("GATEWAY-IP", "GATEWAY-IP"),
("MGT-IP", "MGT-IP"),
("PRIMARY-IP", "PRIMARY-IP"),
("OTHER-IP", "OTHER-IP"),
]
ip_type = models.CharField(verbose_name="IP TYPE",max_length=30,choices=TYPE_CHOICES)
ip = models.ForeignKey(IP,verbose_name="IP",on_delete=models.CASCADE,related_name="asset_ip_set")
asset = models.ForeignKey(Asset,verbose_name="HOSTNAME",on_delete=models.CASCADE,related_name="asset_ip_set")
class Asset(models.Model):
barcode = models.CharField(verbose_name="Barcode",max_length=60,blank=True,null=True,unique=True)
hostname= models.CharField(verbose_name="Hostname",max_length=30)
so in this model data is blow
IP Model
| IP | Asset | Description |
|:---- |:------:| -----:|
| 10.10.10.2 | A_HOST,B_HOST,C_HOST | - |
| 10.10.10.3 | A_HOST,B_HOST | - |
| 10.10.10.4 | A_HOST | - |
| 10.10.10.5 | A_HOST | - |
AssetIP through Model
| IP | Asset | IP_TYPE |
|:---- |:------:| -----:|
| 10.10.10.2 | A_HOST | OTHER-IP |
| 10.10.10.2 | B_HOST | OTHER-IP |
| 10.10.10.2 | C_HOST | OTHER-IP |
| 10.10.10.3 | A_HOST | OTHER-IP |
| 10.10.10.4 | A_HOST | OTHER-IP |
| 10.10.10.5 | A_HOST | PRIMARY-IP |
So Asset Query Result in this
Result = Asset.objects.all()
in this result Field
Asset = {
barcode: "ddd",
hostname: "A_HOST",
}
I Want Field and Result
Asset = {
barcode: "ddd",
hostname: "A_HOST",
primary_ip : "10.10.10.5",
other_ip : "10.10.10.2, 10.10.10.3, 10.10.10.4"
}
I Try the this query in this queryset is not filtering "OHTER-IP"
assets = Asset.objects.annotate(other_ips=GroupConcat('asset_ip_set__ip__ip'))
assets[0].other_ips
result : '10.10.10.2,10.10.10.3,10.10.10.4,10.10.10.5'
and try to this queryset
filtered_ips = AssetIP.objects.filter(asset=OuterRef('pk'), ip_type="OTHER-IP").values_list('ip__ip', flat=True)
Asset.objects.filter(asset_ip_set__ip_type="OTHER-IP").annotate(
other_ips=GroupConcat(
Subquery(filtered_ips),
delimiter=', '
)
)
result : django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row')
Help me....

Power BI - M query to join records matching range

I have an import query (table a) and an imported Excel file (table b) with records I am trying to match it up with.
I am looking for a method to replicate this type of SQL in M:
SELECT a.loc_id, a.other_data, b.stk
FROM a INNER JOIN b on a.loc_id BETWEEN b.from_loc AND b.to_loc
Table A
| loc_id | other data |
-------------------------
| 34A032B1 | ... |
| 34A3Z011 | ... |
| 3DD23A41 | ... |
Table B
| stk | from_loc | to_loc |
--------------------------------
| STKA01 | 34A01 | 34A30ZZZ |
| STKA02 | 34A31 | 34A50ZZZ |
| ... | ... | ... |
Goal
| loc_id | other data | stk |
----------------------------------
| 34A032B1 | ... | STKA01 |
| 34A3Z011 | ... | STKA02 |
| 3DD23A41 | ... | STKD01 |
All of the other queries I can find along these lines use numbers, dates, or times in the BETWEEN clause, and seem to work by exploding the (from, to) range into all possible values and then filtering out the extra rows. However I need to use string comparisons, and exploding those into all possible values would be unfeasable.
Between all the various solutions I could find, the closest I've come is to add a custom column on table a:
Table.SelectRows(
table_b,
(a) => Value.Compare([loc_id], table_b[from_loc]) = 1
and Value.Compare([loc_id], table_b[to_loc]) = -1
)
This does return all the columns from table_b, however, when expanding the column, the values are all null.
This is not very specific "After 34A01 could be any string..." in trying to figure out how your series progresses.
But maybe you can just test for how a value "sorts" using the native sorting function in PQ.
add custom column with table.Select Rows:
= try Table.SelectRows(TableB, (t)=> t[from_loc]<=[loc_id] and t[to_loc] >= [loc_id])[stk]{0} otherwise null
To reproduce with your examples:
let
TableB=Table.FromColumns(
{{"STKA01","STKA02"},
{"34A01","34A31"},
{"34A30ZZZ","34A50ZZZ"}},
type table[stk=text,from_loc=text,to_loc=text]),
TableA=Table.FromColumns(
{{"34A032B1","34A3Z011","3DD23A41"},
{"...","...","..."}},
type table[loc_id=text, other data=text]),
//determine where it sorts and return the stk
#"Added Custom" = Table.AddColumn(#"TableA", "stk", each
try Table.SelectRows(TableB, (t)=> t[from_loc]<=[loc_id] and t[to_loc] >= [loc_id])[stk]{0} otherwise null)
in
#"Added Custom"
Note: if the above algorithm is too slow, there may be faster methods of obtaining these results

Django annotate StrIndex for empty fields

I am trying to use Django StrIndex to find all rows with the value a substring of a given string.
Eg:
my table contains:
+----------+------------------+
| user | domain |
+----------+------------------+
| spam1 | spam.com |
| badguy+ | |
| | protonmail.com |
| spammer | |
| | spamdomain.co.uk |
+----------+------------------+
but the query
SpamWord.objects.annotate(idx=StrIndex(models.Value('xxxx'), 'user')).filter(models.Q(idx__gt=0) | models.Q(domain='spamdomain.co.uk')).first()
matches <SpamWord: *#protonmail.com>
The query it is SELECT `spamwords`.`id`, `spamwords`.`user`, `spamwords`.`domain`, INSTR('xxxx', `spamwords`.`user`) AS `idx` FROM `spamwords` WHERE (INSTR('xxxx', `spamwords`.`user`) > 0 OR `spamwords`.`domain` = 'spamdomain.co.uk')
It should be <SpamWord: *#spamdomain.co.uk>
this is happening because
INSTR('xxxx', '') => 1
(and also INSTR('xxxxasd', 'xxxx') => 1, which it is correct)
How can I write this query in order to get entry #5 (spamdomain.co.uk)?
The order of the parameters of StrIndex [Django-doc] is swapped. The first parameter is the haystack, the string in which you search, and the second one is the needle, the substring you are looking for.
You thus can annotate with:
from django.db.models import Q, Value
SpamWord.objects.annotate(
idx=StrIndex('user', Value('xxxx'))
).filter(
Q(idx__gt=0) | Q(domain='spamdomain.co.uk')
).first()
Just filter rows where user is empty:
(~models.Q(user='') & models.Q(idx__gt=0)) | models.Q(domain='spamdomain.co.uk')

How to calculate number of non blank rows based on the value using dax

I have a table with numeric values and blank records. I'm trying to calculate a number of rows that are not blank and bigger than 20.
+--------+
| VALUES |
+--------+
| 2 |
| 0 |
| 13 |
| 40 |
| |
| 1 |
| 200 |
| 4 |
| 135 |
| |
| 35 |
+--------+
I've tried different options but constantly get the next error: "Cannot convert value '' of type Text to type Number". I understand that blank cells are treated as text and thus my filter (>20) doesn't work. Converting blanks to "0" is not an option as I need to use the same values later to calculate AVG and Median.
CALCULATE(
COUNTROWS(Table3),
VALUE(Table3[VALUES]) > 20
)
OR getting "10" as a result:
=CALCULATE(
COUNTROWS(ALLNOBLANKROW(Table3[VALUES])),
VALUE(Table3[VALUES]) > 20
)
The final result in the example table should be: 4
Would be grateful for any help!
First, the VALUE function expects a string. It converts strings like "123"into the integer 123, so let's not use that.
The easiest approach is with an iterator function like COUNTX.
CountNonBlank = COUNTX(Table3, IF(Table3[Values] > 20, 1, BLANK()))
Note that we don't need a separate case for BLANK() (null) here since BLANK() > 20 evaluates as False.
There are tons of other ways to do this. Another iterator solution would be:
CountNonBlank = COUNTROWS(FILTER(Table3, Table3[Values] > 20))
You can use the same FILTER inside of a CALCULATE, but that's a bit less elegant.
CountNonBlank = CALCULATE(COUNT(Table3[Values]), FILTER(Table3, Table3[Values] > 20))
Edit
I don't recommend the CALCULATE version. If you have more columns with more conditions, just add them to your FILTER. E.g.
CountNonBlank =
COUNTROWS(
FILTER(Table3,
Table3[Values] > 20
&& Table3[Text] = "xyz"
&& Table3[Number] <> 0
&& Table3[Date] <= DATE(2018, 12, 31)
)
)
You can also do OR logic with || instead of the && for AND.

Pyspark filter dataframe by columns of another dataframe

Not sure why I'm having a difficult time with this, it seems so simple considering it's fairly easy to do in R or pandas. I wanted to avoid using pandas though since I'm dealing with a lot of data, and I believe toPandas() loads all the data into the driver’s memory in pyspark.
I have 2 dataframes: df1 and df2. I want to filter df1 (remove all rows) where df1.userid = df2.userid AND df1.group = df2.group. I wasn't sure if I should use filter(), join(), or sql For example:
df1:
+------+----------+--------------------+
|userid| group | all_picks |
+------+----------+--------------------+
| 348| 2|[225, 2235, 2225] |
| 567| 1|[1110, 1150] |
| 595| 1|[1150, 1150, 1150] |
| 580| 2|[2240, 2225] |
| 448| 1|[1130] |
+------+----------+--------------------+
df2:
+------+----------+---------+
|userid| group | pick |
+------+----------+---------+
| 348| 2| 2270|
| 595| 1| 2125|
+------+----------+---------+
Result I want:
+------+----------+--------------------+
|userid| group | all_picks |
+------+----------+--------------------+
| 567| 1|[1110, 1150] |
| 580| 2|[2240, 2225] |
| 448| 1|[1130] |
+------+----------+--------------------+
EDIT:
I've tried many join() and filter() functions, I believe the closest I got was:
cond = [df1.userid == df2.userid, df2.group == df2.group]
df1.join(df2, cond, 'left_outer').select(df1.userid, df1.group, df1.all_picks) # Result has 7 rows
I tried a bunch of different join types, and I also tried different
cond values:
cond = ((df1.userid == df2.userid) & (df2.group == df2.group)) # result has 7 rows
cond = ((df1.userid != df2.userid) & (df2.group != df2.group)) # result has 2 rows
However, it seems like the joins are adding additional rows, rather than deleting.
I'm using python 2.7 and spark 2.1.0
Left anti join is what you're looking for:
df1.join(df2, ["userid", "group"], "leftanti")
but the same thing can be done with left outer join:
(df1
.join(df2, ["userid", "group"], "leftouter")
.where(df2["pick"].isNull())
.drop(df2["pick"]))