I'm trying to set up a filter query in one of my views...basically my code looks as below:
def inventory(request):
vehicle = Vehicle.objects.all().exclude(status__status='Incoming').order_by('common_vehicle__series__model__manufacturer__manufacturer', 'common_vehicle__series__model__model', 'common_vehicle__year')
year_count = Vehicle.objects.exclude(status__status='Incoming').order_by('-common_vehicle__year__year').values('common_vehicle__year__year').annotate(count=Count('id'))
make_count = Vehicle.objects.exclude(status__status='Incoming').order_by('common_vehicle__series__model__manufacturer__manufacturer').values('common_vehicle__series__model__manufacturer__manufacturer').annotate(count=Count('id'))
return render_to_response('vehicles.html', {'vehicle': vehicle, 'make_count': make_count, 'year_count': year_count,})
def year_filter(request, year):
vehicle = Vehicle.objects.filter(common_vehicle__year__year=year)
return render_to_response('filter.html', {'vehicle':vehicle,})
def make_filter(request, make):
vehicle = Vehicle.objects.filter(common_vehicle__series__model__manufacturer__manufacturer=make).exclude(status__status='Incoming')
return render_to_response('filter.html', {'vehicle':vehicle,})
So far when I try any of the last two views, I'm only getting the query set from the first view i.e. inventory. The URLConf file looks as below:
(r'^inventory/year/(?P<year>d{4})/?$', 'app.vehicles.views.year_filter'),
(r'^inventory/make/(?P<make>)/', 'app.vehicles.views.make_filter'),
It looks to me like you're missing an expression.
(r'^inventory/year/(?P<year>d{4})/?$', 'app.vehicles.views.year_filter'),
(r'^inventory/make/(?P<make>)/', 'app.vehicles.views.make_filter'),
<year> matches a series of 4 digits, what does <make> match?
(r'^inventory/make/(?P<make>[-\w]+)/', 'app.vehicles.views.make_filter'),
That matches something to the make variable. Happy to know if I'm wrong!
It looks like in your URLConf, above the ones you have already mentioned, you might have a mapping which overrides the ones below -
say like -
(r'^inventory/', 'app.vehicles.views.inventory'),
which is causing all the calls in inventory to hit the method inventory.
This is because Django goes through it in a serial fashion. Any URL which matches it first will hit it.
To overcome this, you reorder the urls in the following way -
(r'^inventory/year/(?P<year>d{4})/?$', 'app.vehicles.views.year_filter'),
(r'^inventory/make/(?P<make>)/', 'app.vehicles.views.make_filter'),
(r'^inventory/', 'app.vehicles.views.inventory'),
Koran is on the right path. Try having this in your URLconf:
(r'^inventory/$', 'app.vehicles.views.inventory'),
(r'^inventory/year/(?P<year>d{4})/?$', 'app.vehicles.views.year_filter'),
(r'^inventory/make/(?P<make>)/', 'app.vehicles.views.make_filter'),
The regex r'^inventory/$' matches strictly just that, nothing past the '/'. This should cause the other URLs to map to the proper views.
d{4} always matches exactly four d's, dddd. Is that what you want?
(r'^inventory/year/(?P<year>d{4})/?$', 'app.vehicles.views.year_filter'),
I suspect you need to escape d with \, compare:
(r'^inventory/year/(?P<year>\d{4})/?$', 'app.vehicles.views.year_filter'),
Related
Searching through a database looking for matches. Need to log the matches as well as though that don't match so I have the full database but those that match I specifically need to know the part that matches.
serv = ['6:00am-9:00pm', 'Unavailable', '7:00am-10:00pm', '8:00am-9:00pm', 'Closed']
if self.serv[datas] == 'Today':
clotime.append('')
elif self.serv[data] == 'Tomorrow':
clotime.append('')
elif self.serv[data] == 'Yesterday':
clotime.append('')
else:
clo = re.findall('-(.*?):', self.serv[data])
clotime.append(clo[0])
The bulk majority of the data ends up running through re.findall but some is still left for the initial if/elif checks.
Is there a way to condense this code down and do it all with re.findall, maybe even with just one line of code. I need the everything(entire database) gone through/logged so I can process through the database correctly when I go to display the data on a map.
Using anchors you can match a whole string
clo = re.search('^(?:To(?:day|morrow)|Yesterday)$|-(.*?):', self.serv[data])
if clo is not None:
clotime.append(clo.group(1))
With your example list:
serv = ['6:00am-9:00pm', 'Unavailable', '7:00am-10:00pm', '8:00am-9:00pm', 'Closed']
clotime = []
for data in serv:
clo = re.search('^(?:To(?:day|morrow)|Yesterday)$|-(.*?):', data)
if clo is not None:
clotime.append(clo.group(1))
print(clotime)
I would try something like this:
clo = re.findall('-(\d+):', self.serv[data])
clotime.append(clo[0] if clo else '')
If I understood your existing code it looks like you want to append an empty string in the cases where a closing hour couldn't be found in the string? This example extracts the closing hour but uses an empty string whenever the regex doesn't match anything.
Also if you're only matching digits it's better to be explicit about that.
I am querying the adwords api via the following AWQL-Query (which works fine):
SELECT AccountDescriptiveName, CampaignId, CampaignName, AdGroupId, AdGroupName, KeywordText, KeywordMatchType, MaxCpc, Impressions, Clicks, Cost, Conversions, ConversionsManyPerClick, ConversionValue
FROM KEYWORDS_PERFORMANCE_REPORT
WHERE CampaignStatus IN ['ACTIVE', 'PAUSED']
AND AdGroupStatus IN ['ENABLED', 'PAUSED']
AND Status IN ['ACTIVE', 'PAUSED']
AND AdNetworkType1 IN ['SEARCH'] AND Impressions > 0
DURING 20140501,20140531
Now i want to exclude some campaigns:
we have a convention for our new campaigns that the campaign name begins with three numbers followed by an underscore, eg. "100_brand_all"
So i want to get only these new campaigns..
I tried lots of different variations for STARTS_WITH but only exact strings are working - but i need a pattern to match!
I already read https://developers.google.com/adwords/api/docs/guides/awql?hl=en and following its content it should be possible to use a WHERE expression like this:
CampaignName STARTS_WITH ['0','1','2','3']
But that doesn't work!
Any other ideas how i can achieve this?
Well, why don't you run a campaign performance report first, then process that ( get the campaign ids you want or don't want) the use those in the "CampaignId IN [campaign ids here] . or CampaignID NOT_IN [campaign ids]
Based on django-schedule. I can't find the guy who made it.
Pardon me if I'm missing something, but I've been trying to get an events occurrences, preferably for a given day.
When I use event.get_occurrence(date), it always returns nothing. But when I use event.get_occurrences(before_date, after_date), suddenly the occurrences on the previously attempted date show up.
Why won't this work with just one datetime object?
This difference is probably in the actual design of these two methods. Frankly, get_occurrence is rather flawed, in general. A method like this should always return something, even if it's just None, but there's scenarios where it doesn't return at all. Namely, if your event doesn't have an rrule, and the date you passed get_occurrence isn't the same as your event's start, then no value is returned.
There's not really anything that can be done about that. It's just flawed code.
Based on the above comment especially in the case when the event doesn't return and occurrence, the following snippet below can force the retrieval of an occurrence especially when you are sure that it exists
from dateutil.relativedelta import relativedelta
def custom_get_occurrence(event,start_date):
occurrence = event.get_occurrence(start_date)
if occurrence is None:
occurrences = event.get_occurrences(start_date, start_date+relative_delta(months=3)
result = filter(lambda x: x.start==start_date,occurrences)
occurence = result[0]
The above code resolves issue that might occur when the default get_occurrence doesn't return a result.
I have this code:
msgs = int(post['time_in_weeks'])
for i in range(msgs):
tip_msg = Tip.objects.get(week_number=i)
it always results in an error saying that no values could be found.
week_number is an integer field. When I input the value of i directly,
the query works.
When i print out the value of i I get the expected values.
Any input at all would be seriously appreciated.
Thanks.
The range function will give you a zero based list of numbers up to and excluding msgs. I guess there is no Tip with week_number=0.
Also, to limit the number of queries you could do this:
for tip in Tip.objects.filter(week_number__lt=msgs):
#do something
or, if you want specific weeks:
weeks=(1,3,5)
for tip in Tip.objects.filter(week_number__in=weeks):
#do something
I am doing tag search function, user could observe a lot of tags, I get it all in one tuple, and now I would like to find all text which include at least one tag from the list.
Symbolic: text__contains__in=('asd','dsa')
My only idea is do loop e.g.:
q = text.objects.all()
for t in tag_tuple:
q.filter(data__contains=t)
For example:
input tuple of tags, ('car', 'cat', 'cinema')
output all messages what contains at least one word from that tuple, so My cat is in the car , cat is not allowed in the cinema, i will drive my car to the cinema
Thanks for help!
Here you go:
filter = Q()
for t in tag_tuple:
filter = filter | Q(data__contains=t)
return text.objects.filter(filter)
A couple of tips:
You should be naming your model classes with a capital (i.e. Text, not text)
You may want __icontains instead if you're not worried about the case
I don't know Django, so I have no idea how to apply this filter, but it seems you want a function like this one:
def contains_one_of(tags, text):
text = text.split() # tags should match complete words, not partial words
return any(t in text for t in tags)