w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Combine __in and contains query filter to make a more complex filter in django
It doesn't seem possible with normal queryset to me, I guess you need to iterate through the list and find the matches, something like: from django.db.models import Q qs = User.objects.all() for fullname in list_of_names: firstname, lastname = fullname.split() qs = qs.filter( Q(first_name__icontains = firstname), Q(last_name__icontains = lastname) ) Another option would be using raw query which can be okay for this case, the query would be something like: SELECT * FROM users WHERE CONCAT(firstname, ' ', lastname) IN (list_of_name) But this is not case insensitive and you should try to avoid raw query anyway.

Categories : Python

Pass input query for Hadoop job with Date filter (mongo.input.query)
Use extended json for Dates and other datatypes which aren't part of native JSON. For example: {"created_at":{"$gt":{"$date":1182470400000}}} (using the long representation of the date).

Categories : Mongodb

How to query Django model using filter
It's always a bit hard to simply guess by the queryset alone, but this should roughly do it: from django.db.models import Count queryset = models.short_url.objects.filter( created_at__month=m, url_hash='DCmuih', ).annotate(click_info_count=Count('click_info__id')) for short_url in queryset: print short_url, short_url.click_info_count

Categories : Python

Django Query Filter by Date
Just come up with something else: by doing a queryset: today= todaydate (use timezone to get it) today_entry = Entry.objects.filter(date1=today).count() can you try? count_reward = Rewards.objects.filter(user=request.user).filter(routine=d).count() Did you import from your models Entry? from models import Entry If you want to get all the object created after 12AM. ( I suppose all elements created or modified today?) my models.py class Mecdatebis(models.Model): text1 = models.CharField(max_length=50) date1 = models.DateTimeField(auto_now=True) def __unicode__(self): return self.text1 i create a model that have a CharField (to recognize if the entry appears in my html for the good one) a DateTimeField(auto_now=True) that create the Timestamp you are looking

Categories : Python

Django, filter and group query results by a field
You should change cast_unique to be a dictionary where you use the cast member as the key. This will allow much greater performance because you won't have to iterate the cast_unique iterable. Also, your use a list comprehension in the if person.people not in [p.people for p in cast_unique]: requires an entire list to be create of people for every iteration for the test; which, could use a lot of memory plus there's no way to short circuit the list comprehension when a match occurs. Still a dictionary is a much better data type to use for this situation. cast_unique = {} for person in cast: if person.people not in cast_unique: cast_unique[person.people] = person else: cast_unique[person.people].role_title = '{0} / {1}'.format(cast_unique[person.people].role_tit

Categories : Python

How to filter a Django query set by passing in a list of options?
You can use __contains or __exact and for case insensitive matches __icontains and __iexact You can use Q model lookups to do an and filtering: options = ['X1', 'X2', 'X3'] qs = [Q(attribute_name=option) for option in options] #or attribute_name__icontains - or whatever query = qs.pop() #get the first element for q in qs: query |= q qs = MyModel.objects.filter(query)

Categories : Python

MDX query to filter dimension on metric values
First, it sounds like you are dividing by 0 in the calculations for your measures. If you can, I would rewrite them to return null where the denominator is 0. This would look something like: IIF([Measures].[denominator] = 0, Null, [Measures].[Numerator/[Measures].[Denominator]) Then you can use Filter. I'm not quite sure I know enough about your cube's structure to write your query, but try something like this: Select { [Measures].[1], [Measures].[2], [Measures].3]} on COLUMNS, { Filter([Roles].[Dimension].[Dimension].members, CoalesceEmpty([Measures].[1],[Measures].[2],[Measures].[3], 0) <> 0) * ({[Roles].[Roster Role].[Roster Role].[Roster Role - Enterprise], [Roles].[Roster Role].[Roster Role].[Roster Role - Group]})} on ROWS FROM [Cuve] WHERE ( [Dates].[Calendar].[Cale

Categories : Sql Server

Default filter values in Kendo grid through Query string
You can take a look at this sample project which shows how to implement server-side paging, sorting and filtering using ASP.NET MVC and Kendo UI (without the ASP.NET MVC wrappers): https://github.com/telerik/kendo-examples-asp-net-mvc/tree/master/grid-crud

Categories : Jquery

cannot pass javascript values from query to websocket
Based on Mathieu 'OtaK' Amiot's simple but effective idea , I make the second query in the "end" event of the first one. So here is the code client.connect(); var query = client.query('SELECT pins.p_name FROM pins WHERE pins.p_id ='+eoid) query.on("row", function (row, result) {result.addRow(row);}); query.on("end", function (result) { for (var i=0; i<result.rows.length; i++) {name = result.rows[0].p_name;} var query2 = client.query('SELECT m_name FROM multi WHERE m_pins ='+eoid) query2.on("row", function (row, result) {result.addRow(row);}); query2.on("end", function (result) { for (var i=0; i<result.rows.length; i++) {mnm.push(result.rows[i].m_name);} connection.send(JSON.stringify({name:name , mnm:mnm}));

Categories : Javascript

How can I include null values in arithmetic query in django
You can check for null values like: Room.objects.filter(surface_area__isnull=True) And combine that with your lte: from django.db.models import Q Room.objects.filter( Q(surface_area__lte=40) | Q(surface_area__isnull=True) )

Categories : Python

How to do a query based on a subtraction result of two datetime objects in a Django query?
You can calculate the datetime for 24 hours ago and then do a gte query against that. from datetime import datetime, timedelta target_time = datetime.now() - timedelta(hours=24) my_items = MyModel.objects.filter(obj_time__gte=target_time)

Categories : Python

How to rewrite Raw SQL Query (MySQL) with Django ORM query?
First, annotate an author queryset with the number of books. from django.db.models import Count authors = Author.objects.annotate(num_books=Count('librarybook') You haven't shown your Django models, so I've had to guess that 'librarybook' is the correct name for the reverse relationship. Then filter on the num_books to find authors with more than two books. authors = Author.objects.annotate(num_books=Count('librarybook').filter(num_books__gt=2) Finally, slice the queryset to limit it to 3 results. authors = Author.objects.annotate(num_books=Count('librarybook').filter(num_books__gt=2)[:3] You can then loop through the resulting authors and access the number of books. for author in authors: print author.name, author.num_books

Categories : Python

updating list values of dictionary with the values of another dictionary and printing the result as the values of first dictionary in python
Well, first off your syntax for defining literal dictionaries is incorrect. Dictionaries are surrounded by curly brackets like this: {} instead of square brackets like this: [] If you want 'Standard_Animator' and 'Extended_Animator' to be keys for lists of colors, you would want to do something like this: legenddict = {"Standard_Animator" : ["blue", 3f7fff, 00bfff, 3fffbf, "green", bfff3f, ffbf00, ff7f00, "red"], "Extended_Animator" : ["lightgray", "blue", 3f7fff, 00bfff, 3fffbf, "green", bfff3f, ffbf00, ff7f00, "red", "magenta"} colordict = {'blue':'ff00ff', 'red':'808080', 'lightgray':'d3d3d3', 'magenta':'00ff00'} So, to print the values in legenddict using the color names in colordict, you can check to see if the colors are keys in colordict, and if so, look up the

Categories : Python

Access Query - Add column to count matching values in another query
If I understood correctly your question you want to perform the first query with a new column showing the number of ip_address in qry_ip_blacklist table. If thats so and tbl_ip_addresses doesn't have more columns this query will do it: SELECT tbl_ip_addresses.ip_address, tbl_ip_addresses.selected, COUNT(qry_ip_blacklist.ip_address ) FROM tbl_ip_addresses LEFT JOIN qry_ip_blacklist ON qry_ip_blacklist .ip_address = tbl_ip_addresses.ip_address WHERE (tbl_ip_addresses.selected=True) GROUP BY tbl_ip_addresses.ip_address, tbl_ip_addresses.selected In case that this query still doesn't work you can do the query for address with blacklist ip address and another one for those who doesn't have: SELECT tbl_ip_addresses.ip_address, tbl_ip_addresses.selected, COUNT(qry_ip_blacklist.ip_address) F

Categories : Ms Access

Why is my SQL Union Query Returning Different Values than my manual SELECT WHERE query?
col1 or col2 or col3, etc = 'entry name' is not the right syntax. It just checks if col1 and col2 have any value. Only the last one in the list is checked against the actual value 'entry name'.

Categories : SQL

Spring-MVC :: How to pass request parameters (or) query string values to another subsequent request?
You could call the underlying method directly So if you have as controller2 : @RequestMapping(value = "/MyURL", method = RequestMethod.POST) public String myMethod(final BaseDTO baseDTO, Model model) {} Inject controller2 into controller1 and call "normally": controller2.myMethod(baseDTO, model);

Categories : Java

How to convert dictionary values into list in Python / Django?
You need to register your function as a template filter. Also, this code will need to be in a module and then imported into your template as such... # custom_filters.py from django import template register = template.Library() @register.filter def all_numbers(data): number_list=[] if isinstance(data, dict): for name, address in data: for street in data.list(): # this will raise an exception number_list.append(street) return number_list # your-template.html {% load custom_filters %} {{ directory.addressbook.items|all_numbers }}

Categories : Python

Django: passing multiple values into the dictionary of the render method
You're using the class-based view IntroView, which you don't pass in symbol_list with, as you identified. Try modifying your view as follows: class IntroView(generic.DetailView): model = Book template_name = 'books/intro.html' def get_context_data(self, **kwargs): context = super(IntroView, self).get_context_data(**kwargs) context['symbol_list'] = Symbol.objects.all().order_by('name') return context

Categories : Python

Rendering dictionary having values in list format in django template
To access array elements on a django template you must refer to them as elem.attribute. In your case, value.0 and value.1. {% for keys, value in url_dict.items %} <tr border = 1px black> <th>{{ keys }}</th> <td>{{ value.0 }}</td> <!--requires value[0] but not working --> <td>{{ value.1 }}</td> <!--not working --> </tr> {% endfor %} This page may help you: Access array elements in a django template Hope this helps,

Categories : Django

Django, filter by multiple values
Contracts.objects.filter(band__in=bands) You might want to add a prefetch_related statement there to prefetch the gigs though, otherwise your template loop will hit the DB once per contract. contracts = Contracts.objects.filter(band__in=bands).prefetch_related()

Categories : Django

Dapper.net use query into the Dictionary
First change your query to be single one: select case when sex = 1 then 'male' when sex = 2 then 'female' when sex = 0 then 'unknown' end as sex, count(*) as cnt from TblRMember group by sex as I see sex is numerical, so you either have to select by coumn with name (sexname?) or change it in your code. After that: var myDictionary = sqlConnection.Query(strSql) .ToDictionary(x => x.sex.ToString(), x => (int)x.cnt);

Categories : C#

Cannot query dictionary key to get value in MongoDB
You're almost there. db.navi.find_one({'match_id': 240720294}) That'll give you the document with the appropriate match_id. Not really clear if you're looking for other values on that document, or something else, but hopefully this can get you started...

Categories : Python

Pass value from query 1 to query 2
So what you want to do is join to sales on the staffId then group. SELECT a.AccNo,a.Name,a.ID,Max(s.Amount) FROM Transaction t INNER JOIN Account a on t.AccNo = a.AccNo INNER JOIN Sales s on s.staffId = a.ID WHERE a.Status = 'Active' GROUP BY a.AccNo,a.Name,a.ID

Categories : Mysql

use SQL Query in asp to populate scripting dictionary
This should do : Set bannedUsersSet = conn.execute "SELECT DISTINCT LOGIN FROM BANNED_USERS /* Here goes your query */" Set bannedUsers = CreateObject("Scripting.Dictionary") While not bannedUsersSet.EOF bannedUsers(bannedUsersSet("LOGIN")) = True bannedUsersSet.MoveNext WEnd bannedUsersSet.close Set bannedUsersSet = Nothing

Categories : SQL

Sqlite query to python dictionary
You are creating your dictionary incorrectly. Use: for row in r: summary = dict(zip(columns, row)) results.append(summary) instead. Your code sets the whole row sequence as the value for each key in Summary, instead of the individual column value, then appending that same dictionary to the results list for each column key..

Categories : Python

Im have a
that i am posting in an INSERT INTO query and I need to be able to nest a query inside of a query?
$username = mysqli_real_escape_string($con,$_SESSION['username']); $userid = mysqli_real_escape_string($con,$_SESSION['userid']); $subject= mysqli_real_escape_string($con,$_POST['subject']); $message= mysqli_real_escape_string($con,$_POST['message']); $sql="INSERT INTO blogposts (name,subject,message,post_time,profPic) SELECT '$username', '$subject', '$message', CURRENT_TIMESTAMP, picture FROM player WHERE user_id = '$user_id';"; $result = mysqli_query($con,$sql); As mentioned in the comments, look into SQL Injection and the mysqli_real_escape_string function (http://php.net/manual/en/mysqli.real-escape-string.php) EDIT: updated to include procedural style escape string and correct syntax

Categories : PHP

Django: How to use django.forms.ModelChoiceField with a Raw SQL query?
Are you sure you actually need a raw query there? Just looking at that query, I can't see any reason you can't just do it with filter(location__city=city_id, available_reserves__gte=0, datetime_from__gt=datetime.datetime.now()). Raw query sets are missing a number of methods that are defined on conventional query sets, so just dropping them in place isn't likely to work without writing your own definitions for all those methods.

Categories : Django

Cast Linq query to class that inherit a dictionary
If your SymbolsWithQuotes is nothing but an empty class, then I suggest you not use it. As you've seen, it makes things a bit difficult. If you just want to create an alias for the name, you could use the using directive: using SymbolsWithQuotes = Dictionary<string, IList<Quotes>;

Categories : C#

Create dictionary of a sqlalchemy query object in Pyramid
well, yes, we can tighten this up a bit. First, this pattern: index = 0 for item in seq: frobnicate(index, item) item += 1 is common enough that there's a builtin function that does it automatically, enumerate(), used like this: for index, item in enumerate(seq): frobnicate(index, item) but, I'm not sure you need it, Associating things with an integer index starting from zero is the functionality of a list, you don't really need a dict for that; unless you want to have holes, or need some of the other special features of dicts, just do: stuff = [] stuff.extend(seq) when you're only interested in a small subset of the attributes of a database entity, it's a good idea to tell sqlalchemy to emit a query that returns only that: query = DBSession.query(Client.

Categories : Python

How to add filter to group_by query
What about appending this: filter_by(type=1) All together: for l, c in session.query(Player.level, func.count(Player.level)). group_by(Player.level).filter_by(type=1).all()

Categories : Python

GAE ndb.query.filter() not working
NDB queries are immutable, and when you call q.filter(Story.wordCount > 900) you're creating a new query, and not assigning it to anything. Re-assigning to your q variable should work for you: q = Story.query() q = q.filter(Story.wordCount > 900) for s in q.fetch(5): print s.title / s.wordCount

Categories : Google App Engine

How to filter a query using the max(date) value
You want to get a queryset result, so you should use annotate(): latest_user = (LogBook_audit.objects .filter(logbook_id=pk, status=undo_rec.status) .annotate(max_log_in=Max('log_in'))) Hope it helps.

Categories : Django

C# query with filter condition
It's actually easier without a linq query, but with a plain old foreach loop. First, let's create a dictionary to group BMW and Audi into a Cars group etc.: var d = new Dictionary<string, List<string>>(); string[] items = {"Cars,BMW", "Cars,Audi", "Animals,Dog"}; foreach (var item in items) { // TODO: use better variable names // you probably use a csv parser for this var s = item.Split(','); // fill the dictionary. if (!d.ContainsKey(s[0])) d[s[0]] = new List<string>(); d[s[0]].Add(s[1]); } Then, the implementation of GetSelectedTypes could look like this: public static IEnumerable<string> GetSelectedTypes(Dictionary<string, List<string>> validTypes, IEnumerable<string> userSelection ) { foreach (var kvp

Categories : C#

Filter query results
Try this:- SELECT * FROM mod_images LEFT JOIN mod_folders ON folder_id = image_folder_id LEFT JOIN mod_cats ON cat_id = folder_cat_id WHERE ((`folder_number` LIKE '%".$search."%') OR (`titule` LIKE '%".$search."%') OR (`description` LIKE '%".$search."%' )) AND `folder_restriction` = '0' LIMIT 2000 or try to remove the OR at the last:- SELECT * FROM mod_images LEFT JOIN mod_folders ON folder_id = image_folder_id LEFT JOIN mod_cats ON cat_id = folder_cat_id WHERE (((`folder_number` LIKE '%".$search."%') OR ('%".$search."%')) OR ((`titule` LIKE '%".$search."%') OR ('%".$search."%')) OR ((`description` LIKE '%".$search."%') OR ('%".$search."%'))) AND `folder_restriction` = '0' LIM

Categories : Mysql

GAE - Java - Best way to do a query filter "LIKE"
That answer is not the same as your question. The query they provide is a prefix query: ie all names that start with "pe". You seem to want a query for all names which contain "pe" anywhere, which is not possible for the reasons explained in the accepted answer to that question. The Search API is indeed the answer to doing this, and the details of how to create documents to represent your datastore objects are contained in the link you posted. (Note this isn't a migration: your data should stay in the datastore, the Search API is a separate system used only for full-text search.)

Categories : Java

Filter with date() on $sql query
Create two variables. Make 1 equal to the 1st day of the year month you want and the 2nd equal to the 1st day of the following year month. Then it's simply this: where timestamp >= your first variable and timestamp < your second variable This approach will handle the time component of your timestamp field and will perform faster than if you try to use functions.

Categories : PHP

Sub query filter in LEFT/RIGHT JOIN
Here is your query, written so I understand it better: select * from tab2 t2 left outer join tab1 t1 on t1.MemNo = t2.MemId where exists (SELECT 1 FROM TAB3 x WHERE x.Col2 = T2.SVID AND x.Col1 = T1.SID ) and T1.MemNo IS NULL The column t1.MemNo is NULL only when the outer join fails to find a match in that table (because it is part of the join condition). When this is NULL then so is T1.SID, so the exists clause will find no rows because one of the AND conditions evaluates to NULL. If you want to handle this case, then you need logic in the exists clause as well: select * from tab2 t2 left outer join tab1 t1 on t1.MemNo = t2.MemId where exists (SELECT 1 FROM TAB3 x WHERE x.Col2 = T2.SVID AND (x.Col1

Categories : SQL

SQL query or Programmatic Filter for Big Data?
If you have bandwidth to burn, and prefer Python to SQL, go ahead and do one big query and filter in Python. Otherwise, you're probably better off with multiple queries. Sorry, no references here. ^_^

Categories : Python

QBO - Issue in SpecifyOperatorOption Query Filter
The SDK is not encoding the request body correctly, so you will need to use DevDefined and deserialize the response with the SDK. Code sample: https://gist.github.com/IntuitDeveloperRelations/6024616

Categories : C#

SOLR fq (filter query not working)
If you wanna appy filter query over all docs in your index, here is syntax for that: http//mysolrserver:8983/solr/select?q=*:*&fq=modelid:810 or in your solrconfig.xml, you can specify your own request handler, with q.alt set to : <requestHandler name="/custom" class="solr.SearchHandler"> <lst name="defaults"> <str name="echoParams">explicit</str> <str name="defType">dismax</str> <str name="qf"> title^5.0 description^1.0 keywords^3.0 </str> <str name="q.alt">*:*</str> <str name="rows">10</str> <str name="fl">*,score</str> </lst> </requestHandler> and then your query will be: http//mysolrserver:8983/solr/custom?fq=modelid:810

Categories : Solr



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.