w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Bug in Django queryset with count?
Ok, So I figured out where my problem was, it was in the init function, I got rid of it and used my manager's code instead, but I still think something is wrong with the queryset on django's side. class EmailChangeLogManager(models.Manager): def get_query_set(self): return super(EmailChangeLogManager, self).get_query_set().filter(state=EmailChangeLog.PENDING) def create_new_request(self, user): request = self.model() salt = hashlib.sha1(str(random.random())).hexdigest()[:5] username = user.username if isinstance(username, unicode): username = username.encode('utf-8') request.token = hashlib.sha1(salt+username).hexdigest() request.user = user request.save() return request EDIT: There seems to

Categories : Django

Django queryset : cannot F() and count at the same time
Actually, I was doing nothing wrong. This was a bug in Django, related to deepcopying too much data when cloning querysets. This has already been fixed in Django 1.6. (the fix will also improve performance a bit)

Categories : Python

django - Filter foreign key in a queryset
latest() is what you need: Returns the latest object in the table, by date, using the field_name provided as the date field. products = Product.objects.filter(price__gte=Decimal(10)).latest('price__created_in')

Categories : Django

Django filter __contains=queryset?
If I follow your question correctly, you can do this by iteratively building up constraints on the queryset: parts_set = car.parts_set.exclude(pk=new_part.pk) price_qs = Price.objects.all() for part in parts_set: price_qs = price_qs.filter(excluded_parts=part) This will require that the prices in the final queryset have all parts from the parts_set result in their excluded_parts field. They can have other parts as well. price_qs should end up returning your desired results: all prices where the excluded_parts is a super set of the specific car parts I don't know of a better way to construct a query requiring that a many-to-many field must contain multiple specific values.

Categories : Python

Django Admin Queryset Filter OR
Sure, just use Q objects and | to combine them. class MyAdmin(admin.ModelAdmin): def queryset(self, request): return super(MyAdmin, self).queryset(request).filter(Q(a=True) | Q(b=True)) https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects Since (a | b) is logically equivalent to ~(~a & ~b) you can also express this with .exclude: return super(MyAdmin, self).queryset(request).exclude(a=False, b=False) Which is clearer depends a bit on what your actual comparison is. And if you've got nullable terms you have to remember that comparisons to null always return False - not a problem for a simple boolean, but it can bite you if you have, say, a nullable numeric field and try to negate a comparison or range.

Categories : Django

how to count the repetition of the elements in a list python, django
Try something like: x = ['raz', 'dwa', 'raz', 'trzy', 'dwa', 'raz', 'trzy', 'cztery'] wynik = {} for i in x: if i in wynik: wynik[i] += 1 else: wynik[i] = 1 print wynik {'cztery': 1, 'dwa': 2, 'raz': 3, 'trzy': 2} and, if you need: import operator wynik_sorted = sorted(wynik.iteritems(), key=operator.itemgetter(1), reverse=True) print wynik_sorted [('raz', 3), ('dwa', 2), ('trzy', 2), ('cztery', 1)]

Categories : Python

Django filter the queryset of ModelChoiceField - what did i do wrong?
In you views.py, you have this line: form = AddGame(request.POST or None, instance=game) So form is a Form object of class AddGame (Side note: you should change the name to AddGameForm to avoid confusion). Since home_team is a field in AddGame class, it's not an attribute in form object. That's why you can't access it via form.home_team. However, Django Form API provides fields attribute to any form object, which is a dict contains all form fields. That's why you can access form.fields['home_team']. And finally since home_team is a ModelChoiceField, it can contain a queryset attribute, that's why you can access form.fields['home_team'].queryset

Categories : Django

How to filter a Django QuerySet's related fields' 'all' or 'none'
cats = Cat.objects.filter(id=-1) # make it an empty queryset temp = Cat.objects.filter(cat_type='normal') for one in temp: cats |= one.lives.filter(state='alive') # set union temp = Cat.objects.filter(cat_type='schroedinger') for one in temp: cats |= one.lives.exclude(state='dead') return cats new answer: cats = Cat.objects.filter(id=-1) # make it an empty queryset temp = Cat.objects.filter(cat_type='normal') for one in temp: if len(one.lives.exclude(state='alive')) == 0: cats |= Cat.objects.filter(id=one.id) temp = Cat.objects.filter(cat_type='schroedinger') for one in temp: if len(one.lives.filter(state='dead')) == 0: cats |= Cat.objects.filter(id=one.id) return cats

Categories : Misc

Django QuerySet: filter by date, then select one more
You probably would not be able to do it with one database call, as there is no way to know what the next date would be ahead of time, unless you do some preprocessing. One way is: next = Resource.objects.filter(date__gt=now()).order_by('date')[:1] archive = Resource.objects.filter(date__lt=now()) qs = list(chain(archive, next)) OR qs = list(archive, next) Another approach involving a quick lookup would be dt = None now = now() next = Resource.objects.filter(date__gt=now()).order_by('date')[:1] if next.exists(): #A quick lookup for the date now = next[0].date archive = Resource.objects.filter(date__lt=now).order_by('date')

Categories : Python

Django - how to filter using QuerySet to get subset of objects?
This is kind of ugly, but works (without any type safety): toy_owners = Toy.objects.values("owner_id") # optionally with .distinct() Kid.objects.filter(id__in=toy_owners) If performance is not an issue, I think @limelights is right. PS! I tested your query on Django 1.6b2 and got the same unnecessary complex query.

Categories : Python

Django Queryset Filter Missing Quotes
This issue is quite interesting, it seems to happen with SQLite only. It's known here: https://code.djangoproject.com/ticket/14091 and in the docs. So basically the query might not be wrong, but when you get the query back with Django it looks wrong: >>> test_list = ['test1', 'test2', 'test3', 'test4', 'test5'] >>> cls.objects.filter(next_task__test__in=test_list).query.__str__() SELECT ... FROM ... WHERE "job"."next_task_id" IN (test1, test2, test3, test4, test5); Work around: if you really think the query is wrong, then provide more quote for the list, something like: >>> test_list = ["'test1'", "'test2'", "'test3'", "'test4'", "'test5'"] >>> cls.objects.filter(next_task__test__in=test_list).query.__str__() SELECT ... FROM ... WHERE "job"."next_

Categories : Python

Django queryset filter trouble of manytomany field
Since you are looking for all tags for a specific article, You can use the Q filter and then chain the Qs tags = ['X1', 'X2', 'X3'] qs = [Q(tags__name=tag.name) for tag in tags] query = qs.pop() #get the first element for q in qs: query &= q articles = Article.objects.filter(query)

Categories : Django

Filter django queryset over a concatenated extra field
You may use DB function concat in extra as i have done this to concat date in my case. Event.objects.all().order_by('-start_time').extra(select={'date':'concat(year(start_time),"/",month(start_time),"/",day(start_time))','time':'concat(hour(start_time),":",minute(start_time))','program_no':'program_id'}).values('id','program_no','event_type__name','venue__city','venue__state','venue__website','series_id','date','time') Hope this will help you. Thanks.

Categories : Django

How to filter a django queryset based on Location coordinates?
If you are going to be handling a lot of data that is geographic in nature, you may consider GeoDjango, which has support for spatial lookups. However, it only works with certain backends, so it may require a lot more to get set up if your stack doesn't meet the requirements. Otherwise, the other option would be to do a little geometry and calculate the bounding circle around your point, and filter on that. Here's an example, and it looks like there are plenty of other writeups on how to do this. EDIT: in response to your question on how to do this, I am assuming you mean the second part. I am not an expert in TastyPie, but it looks like you will have to this in your view: Get the user's lat an longitude coordinates Calculate a distance -- it looks like you can do this natively in S

Categories : Python

Django queryset - Return only matching manytomany records when applying filter on object
Why do you want that all in one queryset ? Venue.objects.get(id=<id_venue1>).event_set.all() should return you all the events linked to venue1 in one queryset, and you can have venue1 in another queryset. You can also use Venue.objects.get(id=<id_venue1>).values('adress', 'phone_number', 'event__name', 'event__description') to get something like the array of dicts bellow: [ { 'adress': '<venue1adress>', 'phone_number': '<venue1phone>', 'event__name': 'foo', 'event__description': 'I am a foo event'}, { 'adress': '<venue1adress>', 'phone_number': '<venue1phone>', 'event__name': 'bar', 'event__description': 'I am a bar event'}, ... ] Finaly , I think, you can also rework the default queryset (since it's a python objects, and with python object

Categories : Django

Django model manager queryset filter on aware datetime: no item display until server restart
I am 99% sure that you have something like that on your models: class News(models.Model): .... publication_date = models.DateTimeField(default=timezone.now()) .... What this actually does it gives a value to keyword argument 'default' instead of passing a function as an object, to be called every time you create a new object. And you want to pass a function 'timezone.now' but not a value of this function, wich would be 'timezone.now()' Change it to this: class News(models.Model): .... publication_date = models.DateTimeField(default=timezone.now) .... And do not forget to apply this everywhere on your code where you want to give default timezone.now value to DateTimeField Cheets! Do not forget to up-vote if you find this answer useful! ;)

Categories : Django

django edit queryset objects without affecting database
One simple method is to convert the queryset to a list. The list will contain instances of your model. You can do whatever you like with those instances and nothing will be saved to the database unless you call save or one of the other methods that writes to the database. dividend_set = stock.dividend_set.all().order_by('date') dividends = list(dividend_set) for dividend in dividends: dividend.extra_value1 = 'foo' dividend.extra_value2 = 'bar' # now pass the dividends list to your template as part of your context rather than the qs

Categories : Python

Python selection on Django queryset Result
There are many, many things wrong with this code. Some of the obvious: Swapping ele and large doesn't actually do anything to the list, it just rebinds the name ele to what was previously large but that name is then immediately rebound to the next element in the list anyway; res[i] will give you an IndexError because the list is empty; you probably want to do res.append(i). However, unless you're doing this as an algorithm learning exercise, I have no idea why you want to do it at all. Python has a perfectly good built-in sort() function, which is many times more efficient than your code - and on top of that, Django's querysets themselves support sorting directly in the database, which is even better.

Categories : Python

Why is quering via a django QuerySet much slower than just using a cursor in Django?
If you timed the two code segments in the update to your question, then yes, the difference is because django is marshalling the results of the DB query into 700,000 python objects (i.e., it's calling object.__init__() 700,000 times). There is nothing wrong with using raw sql for the query. This is a case where it might be advised, depending on what you do with the info. That said .... do you need 700,000 objects in the response? Will 700,000 items in a dict do instead (that's what the raw sql query returns)? Or can you limit the rows you get back with pagination or query-set slicing?

Categories : Django

Python django how to properly test if a queryset returned a result
You can use .filter() instead of .get(), and also make use of django's optimized queryset evaluation. You can do qs = User.objects.filter(email=email) if qs : user = qs[0] ...

Categories : Python

How to combine/merge more than one queryset in to single queryset django
Use the | operator. i.e queryset = queryset1 | queryset2 | queryset3 But you can also use the & operator to find intersection. You have to make sure that all the querysets return are of the same objects i.e Tag. What you want to do basically is queryset = entries[0].tags.all() for entry in entries[1:]: queryset = queryset | entry.tags.all()

Categories : Python

Total Count In Django
Use category.entry_set.count instead of category.entry_set.all.count. Also, you are using same variable name category for referencing multiple values, you may want to change that. Update template as: <ul> {% for cat in category %} <li><a href="{{ cat.slug }}">{{ cat.title }}</a> ({{ cat.entry_set.count }})</li> {% endfor %} </ul>

Categories : Django

Django Celery get task count
If your broker is configured as redis://localhost:6379/1, and your tasks are submitted to the general celery queue, then you can get the length by the following means: import redis queue_name = "celery" client = redis.Redis(host="localhost", port=6379, db=1) length = client.llen(queue_name) Or, from a shell script (good for monitors and such): $ redis-cli -n 1 -h localhost -p 6379 llen celery

Categories : Python

Django get count based on foreign Key for every month
Just make a query with time range: import datetime from models import click_info def get_click_by_month(month, year, hash): d1 = datetime.datetime(year=year, month=month, day=1) d2 = datetime.datetime(year=year, month=month + 1, day=1) clicks = click_info.objects.filter(url_hash=hash, created_at__range=[d1, d2]) return len(clicks) P.S. PEP8 recommends to use CamelCase to name classes. Of course it's not obligatory but at least people inside the team must use same principles of code writing. Using PEP8 is just easier than creating your own rules.

Categories : Python

Where do I put a function to count foreign keys in Django?
If the result involves multiple rows, it is a table-related method, and according to Django conventions, should be a manager method. From the Django docs: Adding extra Manager methods is the preferred way to add “table-level” functionality to your models. (For “row-level” functionality – i.e., functions that act on a single instance of a model object – use Model methods, not custom Manager methods.)

Categories : Python

fetch data using count function in django
The count() method does not take any arguments. You can filter the queryset first, then use count. For example: published_count = Book.objects.filter(published=True).count()

Categories : Python

filter the data from database using django filter
Your form is using location ids for its value keys, not location titles. ChoiceFields use the first part of each tuple in choices as the value which gets POSTed and the second part of each tuple is just the name of the choice as the user sees it. Add a print statement to check the value of your loc_id and you'll see what I mean. So you'll want to look up a location title for the location id in request.POST. If your ReportLocation model has a ForeignKey to Location you can do something like location_list = ReportLocation.objects.filter(location__id=loc_id) but if that doesn't work with your schema you might have to look up the title as a separate query. Here's a simplistic example: def search(request): reportlist = [] loc_id = request.POST.get('location') if loc_id:

Categories : Django

Django, display count of unread messages in base template
You can write a simple tag which can do this for you. def unread_messages(user): return user.messages_set.filter(read=False).count() #replace the messages_set with the appropriate related_name, and also the filter field. (I am assuming it to be "read") register.simple_tag(unread_messages) and in the base template: {% load <yourtemplatetagname> %} {% if request.user.is_authenticated %} {{ request.user|unread_messages }} {% endif %}

Categories : Django

Usage of a COUNT(DISTINCT field) with a GROUP BY clause in Django
The annotate method of a queryset will calculate an aggregate value for each element of the queryset, and when used after a values call will aggregate over the values of the values. I think this should work: qs = models.Site.objects.filter(user__device__applicationusage__activity__range=[startDay, endDay]).values('name').annotate(Count('user__device', distinct=True)) If you have an ordering specified you may need to remove it as discussed here: https://docs.djangoproject.com/en/dev/topics/db/aggregation/#interaction-with-default-ordering-or-order-by

Categories : Mysql

Django ordering parent model by count of children models in (one to many relation)
child_set is the default related_name of your parent field in the Child model. If you've specified a different one, you will have to change the code accordingly. from django.db.models import Count ordered_parents = Parent.objects.annotate(num_children=Count('child_set')).order_by('-num_childen') Hope it helps.

Categories : Django

Django Templates: Output count of Filtered Through Relationship Attached Objects
One way you can do it is: class Project(models.model): ... desings = models.ManyToManyField(Design, through="ProjectDesign") ... def design_count(self): return self.desings.filter(desings__published=True) and in the template {% if project.design_count %} The other way is, you can write a custom manager for Design model which returns only the published designs. Then your query would be as simple as {% if project.desings.all %}

Categories : Django

Row count column count in all tables in Sybase database
Sybase ASA has a bunch of system tables providing you with information about the structure of your database. The two tables that are of interest for you are SYSTABLE (all tables) and SYSCOLUMN (all columns). I tried this quick and dirty stored procedure that works for me (on the rather aged ASA version 8!). It creates a temporary table and a cursor to iterate over all tables. For every table the table name, number of columns and number of rows are inserted into the temp table and finally returned. (Hint: the tablefilter allows to return only a subset of the whole database, if you have many tables.) CREATE PROCEDURE Usr_TableStats(in par_tablefilter char(100)) RESULT (tablename varchar(255), number_of_cols int, number_of_rows int) BEGIN declare err_notfound exception for sqlstate va

Categories : SQL

Python .count: Can't find correct syntax to count
list.count is used to get the count of an item in list, but you need to do a substring search in each item to get the count as 4. >>> data = ['This','is','some','test','data',' This','is','some','test','data',' This','is','some','test','data',' This','is','some','test','data',' '] Total number of items that contain ' ': >>> sum(' ' in item for item in data) 4 Sum of count of all ' 's in data: >>> data = [' foo',' bar'] >>> sum(item.count(' ') for item in data) 5

Categories : Python

how do you change a database filter based on a link you click in django?
Basically, you can make this work by using named groups in your urls.py patterns, e.g.: (r'^links/(?P<value>w+)/$', display) Then, you can access saved part of url inside your view, like: def display(request, value=None): print value And, of course, you should use appropriate url in the template: <td><a href="links/{{ status.rootgroup }}/"> {{ status.rootgroup }} </a></td> Also see documentation.

Categories : Python

Disqus count.js returns the wrong comment count and reaction count
Specify the absolute URL associated with that thread in your comment count href link instead of the relative url which you are currently using. The absolute URL should would be: <a href="http://in-the-attic.com/2013/01/04/building-a-blog-using-jekyll-bootstrap-and-github-pages-a-beginners-guide/">Comments</a> If you are still not seeing the correct count display for that particular thread, you can use an identifier: <a href="http://in-the-attic.com/2013/01/04/building-a-blog-using-jekyll-bootstrap-and-github-pages-a-beginners-guide/" data-disqus-identifier="EXAMPLE">Comments</a> Keep in mind that you cannot use the identifier until you have set one for that thread within the Javascript configuration variables

Categories : Misc

django - how to get value of key-value queryset from values()
Use dot notation in Django templates: {{ object.column }} Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order: Dictionary lookup. Example: foo["bar"] Attribute lookup. Example: foo.bar List-index lookup. Example: foo[bar]

Categories : Python

how to get day name from queryset in django template?
There is a Django date template filter: {{ model.field|date:'l' }} Docs here.

Categories : Python

django queryset - hitting the db in O(1)
Use latest("execution_end_date") on your queryset: lji = JobInstance.objects.filter(job_type=job_type, agent=agent).latest('execution_end_date') Or add it to your model's Meta class like so: class JobInstance(models.Model): .... class Meta: get_latest_by = "execution_end_date"

Categories : Python

queryset django relationship
Filter using __isnull: Normally, Django automatically follows relationship fields using the lowercased name of the related model: Income.objects.filter(invoice__isnull=True) Here, you've specified the related_name attribute, so you need to use that: Income.objects.filter(Income__isnull=True) Note that this reveals that your related name attribute for the income FK on Invoice is backwards. I see no reason for you to be setting a related_name at all, but if you do need one it should describe how the invoices are related to incomes, not vice versa.

Categories : Python

Django Queryset for date
Try this: from datetime import datetime, timedelta Example.objects.filter(date_created__lte=datetime.utcnow() - timedelta(days=6*30)).delete()

Categories : Python



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