Count multiple terms - django

class Term(models.Model):
created = models.DateTimeField(auto_now_add=True)
term = models.CharField(max_length=255)
Hey Guys,
I try to Count duplicate/multiple terms from my db table but I get still a list of all items ({term: a, count: 1, term: a, count: 1,term: b, count: 1,...}) of my table and not like {term: a, count: 12, term: b, count: 1}
Has anyone an idea?
EDIT:
ee = Term.objects.annotate(Count("term")).values("term", "term__count")
Result:
[{'term': u'tes', 'term__count': 1}, {'term': u'tes', 'term__count': 1},
What I expected:
[{'term': u'tes', 'term__count': 2}, {'term': 'b', 'term__count': 1}

https://docs.djangoproject.com/en/dev/topics/db/aggregation/
says about the order being important. Also, if you have an order_by on the model, that will affect it.
How about ...
ee = Term.objects.values("term").annotate(Count("term")).order_by()

In SQL you cannot do that in only one query, you need a sub query. I guess it is the same with Django, so try this:
ee = Term.objects.extra(select={'count': "SELECT COUNT(term) FROM appname_term AS subtable WHERE subtable.term = appname_term.term"})
It should add a count attribute to every term from ee with the number of rows with this. It applies a subquery on the same relation in the main query. It's equivalent of SQL:
SELECT *, (
SELECT COUNT(term)
FROM appname_term AS subtable
WHERE subtable.term = appname_term.term
) AS count
FROM appname_term

Related

Fetch for value and convert it to another according to condition

SHEET A - origin
Column A = ID
Column B = can contain "Accepted"(+ more text), "Rejected"(+more text), "Partially Accepted"(+ more text)
SHEET B - destination
Column A = Column A from Sheet A
Column B = If Column B from Sheet A = "Accepted*" return 1, "Rejected*" return 2, "Partially*" return 3, else return 4
WHAT I've tried so far:
a) Works but I can't make it into an array
=IF(COUNTIF(SHEETA!A2,"*Rejected*"),2,IF(COUNTIF(SHEETA!A2,"*Partially*"),3,IF(COUNTIF(SHEETA!A2,"Accepted*"),1,4)))
b) Been trying to make it work (simplified version) but it's not working
=if((VLOOKUP(A2,A2:B2,2,FALSE))="Rejected*","2","1")
Can anyone give me a hand?
Thank you in advance
try in row 2:
=INDEX(IFNA(VLOOKUP(A2:A, {SheetA!A2:A, IFNA(CHOOSE(MATCH(
REGEXEXTRACT(SheetA!B2:B, "(?i)accepted|rejected|partially accepted"),
{"accepted", "rejected", "partially accepted"}, ), 1, 2, 3), 4)}, 2, )))

Django filtering with list and specific data

I'm sorry for the weird title. I don't know how to explain my problem in a short sentence. I'm trying to filter my model with a list but sometimes query returns multiple rows. For example:
all_pos [1,2,3]
query = MyModel.objects.filter(pos__in=all_pos)
The query above returns a list of rows from the database but second item in the list returns two rows with B and C in the second column.
1, A, word
2, B, word
2, C, word
3, A, word
4, C, word
But I only want the row with B on the second row and not losing 4th row with C. How can I filter this further so I can achieve the result below.
1, A, word
2, B, word
3, A, word
4, C, word
Your specifications are still not very clear. You need to specify by what logic you keep a result vs other.
But what I deduce, is you want the results ordered by col 1 ASC and col 2 alphabetically and distinct on col 1.
all_pos = [1, 2, 3, 4]
query = MyModel.objects.filter(pos__in=all_pos).order_by('col1', 'col2').distinct('col1')
Otherwise you will need 2 passes maybe like:
all_pos = [1, 2, 3, 4]
final_results = []
qs = MyModel.objects.filter(pos__in=all_pos)
for row in col1_qs:
if custom_logic_with(row.col2):
final_results.append(row)

Coldfusion loop query results and update using dynamic column names

In the database I have 5 columns plus the id:
id, m1, m2, m3, m4, m5
I'm selecting from one table that may have from 1 to 5 rows based on the id:
row,id,value
1, 1, 'A'
2, 1, 'B'
3, 1, 'C'
etc
What I need to do is update columns m1, m2 and m3 in the user table for user ID 1 with values A, B and C. I've started down the path of something like this but am hitting serious Monday brain on a Tuesday.
i=1;
cfloop (query=q) {
field = 'm' & i;
temp = invoke(myCFC,"updateUser",{ userid=q.id, field = q.value });
i++;
};
Where 'field' would be m1, m2, m3. One way would be to use a switch/case on the recordcount and have 5 different invokes, but not sure if there would be a better way programatically?
[edit] this works but may not be the best way - I have cases for 1-5:
switch(qryM.recordCount) {
case "1":
temp = invoke(userCFC,"updateUser", {
id = qryM.rsm_userid,
m1_c = qryM["rsm_c"][1],
m1_m = qryM["rsm_m"][1]
});
break;
case "2":
temp = invoke(userCFC,"updateUser", {
id = qryM.rsm_userid,
m1_c = qryM["rsm_c"][1],
m1_m = qryM["rsm_m"][1],
m2_c = qryM["rsm_c"][2],
m2_m = qryM["rsm_m"][2]
});
break;
If there really can only ever be a maximum of five rows and the target column always is "m" + the current row number, then this would work:
for (row in q) {
myCFC.updateUser(userid:row.id, field:'m#q.CurrentRow#');
}

What GROUPBY aggregator can I use to test if grouped values are equal to a constant?

Situation: I have table Bob where each row has a bunch of columns, including a Result, SessionID1, SessionID2.
Goal: I want to GroupBy SessionID1 and SessionID2 and see if any Results in the group are 0; I expect multiple rows to have the same ID1 and ID2 values. I then want to divide the count of groups with 0 results / the count of all groups.
Questions: I think I want something like:
GROUPBY (
Bob,
SessionID1,
SessionID2,
"Has at least 1 success",
???)
But what aggregator can I use for ??? to get a boolean indicating if any result in the group equals 0?
Also, if I want a count of groups with successes, do I just wrap the GROUPBY in a COUNT?
Consider this sample table:
You can try the following DAX to create a new summary table:
Summary = GROUPBY(Bob, Bob[SessionID1], Bob[SessionID2],
"Number of rows", COUNTX(CURRENTGROUP(), Bob[Result]),
"Number of successes", SUMX(CURRENTGROUP(), IF(Bob[Result] = 0, 1, 0)))
Then you can add a calculated column for the success ratio:
Success ratio = Summary[Number of successes] / Summary[Number of rows]
Results:
EDIT:
If what you want to calculate is something like Any success, then SUMMARIZE may be a better option to use than GROUPBY due to their function nature.
Summary2 = SUMMARIZE(Bob, Bob[SessionID1], Bob[SessionID2],
"Any success", IF(COUNTROWS(FILTER(Bob, Bob[Result] = 0)) > 0, 1, 0),
"Number of rows", COUNTROWS(Bob))
Results:

How do I do a where OR on two columns in the same table?

I have a membership model, and I want to search OR on two columns....not sure how to do it.
I tried this:
u1.all_memberships.where(inviter: u2, invited: u2)
Membership Load (6.8ms) SELECT "memberships".* FROM "memberships" WHERE (memberships.user_id = 1 OR memberships.invited_id = 1) AND "memberships"."user_id" = 3 AND "memberships"."invited_id" = 3
=> []
But note the 2 AND on both queries, when ideally what I would like to do is literally just replace all the ANDs with ORs.
So I would love if the query looked something like this:
Membership Load (6.8ms) SELECT "memberships".* FROM "memberships" WHERE (memberships.user_id = 1 OR memberships.invited_id = 1) OR (memberships.user_id = 3 OR memberships.invited_id = 3)
Assuming that my modification is syntactically correct SQL ofcourse.
How do I do that with a where clause? Is that possible?
I expect It can help
where("inviter_id = ? OR invited_id = ? ", u2.id, u2.id)
DRYer solution
where("inviter_id = :uid OR invited_id = :uid ", uid: u2.id)