Maybe the solution is to do it with Filter and then loop. But let's see if you guys can tell me a way to do it with GET
I have this query with GET as I need to be sure I get only one result
result = OtherModel.objects.get(months_from_the_avail__lte=self.obj.months_from_avail)
Months_from_avail is an Integer value.
Example
months_from_the_avail = 22
In the other model there's 3 lines.
A) months_from_the_avail = 0
B) months_from_the_avail = 7
C) months_from_the_avail = 13
So, when I query it returns all of them as all are less than equal the value 22 but I need to get the 13 as is the last range.
range 1 = 0-6
range 2 = 7-12
range 3 = 13 ++
Is there any way that I haven't thought to do it? Or should I change it to filter() and then loop on the results?
you can get the first() section from the query order_by months_from_the_avail
Remember that django query are lazy, it won't execute until the query if finished calling so you can still use filter:
result = OtherModel.objects.filter(months_from_the_avail__lte=self.obj.months_from_avail).order_by('-months_from_the_avail').first()
#order by descending get first object which is the largest, return None if query set empty
another suggestion from Abdul which i think it's faster and better is using latest()
OtherModel.objects.latest('-months_from_the_avail')
Related
I'm filtering a query set to get the number of visitors and pageviews but when there is no data it returns None.
How to get 0 instead of None when filtering a queryset when there is no data?
yesterday_visitors = queryset.filter(date__gte=yesterday, page=None).aggregate(Sum('visitors'))
yesterday_page_views = queryset.filter(date__gte=yesterday, page=None).aggregate(Sum('page_views')) ```
I've finally ended up doing it another way that is probably the easiest one, by just adding "or 0" at the end while use get __sum on "visitors" and "page_views" :
yesterday_visitors = queryset.filter(date__gte=yesterday, page=None).aggregate(Sum('visitors')).get('visitors__sum') or 0
yesterday_page_views = queryset.filter(date__gte=yesterday, page=None).aggregate(Sum('page_views')).get('page_views__sum') or 0
I have been trying to make this regular expression REGEX filter work in Google Data Studio. It is supposed to do the following
Check the field "src_id" and COUNT all the values containing "widget".
Check the field "Page" and COUNT all the values starting with a "/" and ending with "/start".
Check the field "real_title" and NOT COUNT any value containing "-".
I have tried using the code below but it's not providing the correct result:
COUNT(CASE WHEN REGEXP_MATCH(src_id, "^widget" ) THEN 1
WHEN REGEXP_MATCH(Page, ".*(/start)$") then 1
WHEN REGEXP_MATCH(real_title, "^[^-]") then 1
ELSE 0 END)
I expect the result to "52" but it's giving me "582. I need help to spot what I'm doing wrong.
The problem is your count() - it is counting all the entries including zeroes.
either use sum() or just use the case statement and sum where you want it .
Examples
TestField1
COUNT(CASE WHEN REGEXP_MATCH(Page Title , "^How.*" ) THEN 1
ELSE 0 END)
This returns 58 - the number of page titles on my site.
TestField2
Sum(CASE WHEN REGEXP_MATCH(Page Title, "^How.*" ) THEN 1
ELSE 0 END)
This returns 7 - the number of titles on the site that start with "How"
You really don't need the sum() function in most cases because you can sum the field in the places you need it.
Can I select a certain row/column combination in coldfusion without doing a query of queries? For example:
Some Query:
ValueToFind | ValueToReturn
String 1 | false
String 2 | false
String 3 | true
Can I somehow do #SomeQuery["ValueToFind=String 3"][ValueToReturn]# = true without doing a query of queries ? I know there's code out there to get a certain row by id, but I'm not sure how or if I can do it when I need a string as the ID
If this can't be done, is there a short hand way to set up a coldfusion function so I can use something like FindValue(Query, "String 3") and not have to use ?
You can treat a query column as an array.
yourRow = ArrayFind(queryName['columnName'], "'the value you seek'");
If you get a zero, the value you seekis not there.
Edit starts here:
For values of other columns in that row, simply use that variable.
yourOtherValue = queryName.otherColumnName[yourRow];
A small modification to Dan's code, you can find the column value using the code below
yourVaue = SomeQuery["ValueToReturn"][ArrayFind(SomeQuery['ValueToFind'], "String 3")]
In our Django project, there is a view which creates multiple objects (from 5 to even 100). The problem is that creating phase takes a very long time.
Don't know why is that so but I suppose that it could be because on n objects, there are n database lookups and commits.
For example 24 objects takes 67 seconds.
I want to speed up this process.
There are two things I think may be worth to consider:
To create these objects in one query so only one commit is executed.
Create a ThreadPool and create these objects parallel.
This is a part of the view which causes problems (We use Postgres on localhost so connection is not a problem)
#require_POST
#login_required
def heu_import(request):
...
...
product = Product.objects.create(user=request.user,name=name,manufacturer=manufacturer,category=category)
product.groups.add(*groups)
occurences = []
counter = len(urls_xpaths)
print 'Occurences creating'
start = datetime.now()
eur_currency = Currency.objects.get(shortcut='eur')
for url_xpath in urls_xpaths:
counter-=1
print counter
url = url_xpath[1]
xpath = url_xpath[0]
occ = Occurence.objects.create(product=product,url=url,xpath=xpath,active=True if xpath else False,currency=eur_currency)
occurences.append(occ)
print 'End'
print datetime.now()-start
...
return render(request,'main_app/dashboard/new-product.html',context)
Output:
Occurences creating
24
.
.
.
0
End
0:01:07.727000
EDIT:
I tried to put the for loop into the with transaction.atomic(): block but it seems to help only a bit (47 seconds instead of 67).
EDIT2:
I'm not sure but it seems that SQL queries are not a problem:
Please use bulk_create for inserting multiple objects.
occurences = []
for url_xpath in urls_xpaths:
counter-=1
print counter
url = url_xpath[1]
xpath = url_xpath[0]
occurances.append(Occurence(product=product,url=url,xpath=xpath,active=True if xpath else False,currency=eur_currency))
Occurence.objects.bulk_create(occurences)
One field in my model is a charField with the format substring1-substring2-substring3-substring4 and it can have this range of values:
"1-1-2-1"
"1-1-2-2"
"1-1-2-3"
"1-1-2-4"
"2-2-2-6"
"2-2-2-7"
"2-2-2-9"
"3-1-1-10"
"10-1-1-11"
"11-1-1-12"
"11-1-1-13"
For example I need to count the single number of occurrences for substring1.
In this case there are 5 unique occurrences (1,2,3,10,11).
"1-X-X-X"
"2-X-X-X"
"3-X-X-X"
"10-X-X-X"
"11-X-X-XX"
Sincerely I don't know where I can start from. I read the doc https://docs.djangoproject.com/en/1.5/ref/models/querysets/ but I didn't find a specific clue.
Thanks in advance.
results = MyModel.objects.all()
pos_id = 0
values_for_pos_id = [res.field_to_check.split('-')[pos_id] for res in results]
values_for_pos_id = set(values_for_pos_id)
How does this work:
first you fetch all your objects (results)
pos_id is your substring index (you have 4 substring, so it's in range 0 to 3)
you split each field_to_check (aka: where you store the substring combinations) on - (your separator) and fetch the correct substring for that object
you convert the list to a set (to have all the unique values)
Then a simple len(values_for_pos_id) will do the trick for you
NB: If you don't have pos_id or can't set it anywhere, you just need to loop like this:
for pos_id in range(4):
values_for_pos_id = set([res.field_to_check.split('-')[pos_id] for res in results])
# process your set results now
print len(values_for_pos_id)
Try something like this...
# Assumes your model name is NumberStrings and attribute numbers stores the string.
search_string = "1-1-2-1"
matched_number_strings = NumberStrings.objects.filter(numbers__contains=search_string)
num_of_occurrences = len(matches_found)
matched_ids = [match.id for match in matched_number_strings]
You could loop through these items (I guess they're strings), and add the value of each substring_n to a Set_n.
Since set values are unique, you would have a set, called Set_1, for example, that contains 1,2,3,10,11.
Make sense?