How to sort by likes or views Flask? - python

I have a problem sorting Authors by Author.likes or Author.views .
Lets me first show you my codes snippets :
views.py
from sqlalchemy import func
#app.route('/authors/')
def authors():
page = request.args.get('page', 1, type=int)
pagination = Author.query.order_by(func.count(Author.likes)).paginate(page, per_page=app.config['AUTHORS_PER_PAGE'], error_out=False)
Here am using the func.count() function to sort the authors ordered by likes.
The problem is am getting just the most liked author , in fact i have 12 of them in the database each one has his likes, so i need to sort them all by likes from the highest one to the lowest .
I tried a different ways but without avail , please any help !

Remove func.count and just order by Author.likes, it's already a count. func.count is for counting groups of things. Currently, you're grouping everything into one group and so you only get one item back.

Related

Using .filter in Django to see if title contains a certain string?

My code is:
posts = Listing.objects.filter(title=q, is_live=1)
I need the equivalent of:
posts = Listing.objects.filter(q in title, is_live=1)
How can I just determine if a certain bit of text exists and isn't exactly equal to the query?
Try this:
posts = Listing.objects.filter(title__contains=q, is_live=1)

Django SearchVector using icontains

I am trying to search for a list of values in multiple columns in postgres (via django). I was able to use SearchQuery and SearchVector and this works great if one of the search values matches a full word. I was hoping to use icontains so that partial strings could also be used in the search. Is this possible and if so could someone point me in the right direction. Here is an example of my approach below.
Example Data:
Superhero.objects.create(
superhero='Batman',
publisher='DC Comics',
alter_ego='Bruce Wayne',
)
Superhero.objects.create(
superhero='Hulk',
publisher='Marvel Comics',
alter_ego='Bruce Banner',
)
Django filter:
from django.contrib.postgres.search import SearchQuery, SearchVector
query = SearchQuery('man') | SearchQuery('Bruce')
vector = SearchVector('superhero', 'alter_ego', 'publisher')
queryset = queryset.annotate(search=vector).filter(search=query)
This would return the Hulk record but I am hoping I can somehow use like 'icontains' so that when searching for 'man' the Batman record would also be returned. Any help is appreciated!
You can apply icontains to the filter like:
queryset = queryset.annotate(search=vector).filter(search__icontains=query)
So SearchQuery and SearchVector are a part of Django's Full Text searching functionality and it doesnt look like you can achieve what I was wanting to do with these functions. I have taken a different approach thanks to Julian Phalip's approach here.. https://www.julienphalip.com/blog/adding-search-to-a-django-site-in-a-snap/

How can I query for multiple properties not known in advance using Expando?

I'm making an application in which a user can create categories to put items in them. The items share some basic properties, but the rest of them are defined by the category they belong to. The problem is that both the category and it's special properties are created by the user.
For instance, the user may create two categories: books and buttons. In the 'book' category he may create two properties: number of pages and author. In the buttons category he may create different properties: number of holes and color.
Initially, I placed these properties in a JsonProperty inside the Item. While this works, it means that I query the Datastore just by specifying the category that I am looking for and then I have to filter the results of the query in the code. For example, if I'm looking for all the books whose author is Carl Sagan, I would query the Item class with category == books and the loop through the results to keep only those that match the author.
While I don't really expect to have that many items per category (probably in the hundreds, unlikely to get to one thousand), this looks inefficient. So I tried to use ndb.Expando to make those special properties real properties that are indexed. I did this, adding the corresponding special properties to the item when putting it to the Datastore. So if the user creates an Item in the 'books' category and previously created in that category the special property 'author', an Item is saved with the special property expando_author = author in it. It worked as I expected until this point (dev server).
The real problem though became visible when I did some queries. While they worked in the dev server, they created composite indexes for each special/expando property, even if the query filters were equality only. And while each category can have at most five properties, it is evident that it can easily get out of control.
Example query:
items = Item.query()
for p in properties:
items = items.filter(ndb.GenericProperty(p)==properties[p])
items.fetch()
Now, since I don't know in advance what the properties will be (though I will limit it to 5), I can't build the indexes before uploading the application, and even if I knew it would probably mean having more indexes that I'm comfortable with. Is Expando the wrong tool for what I'm trying to do? Should I just keep filtering the results in the code using the JsonProperty? I would greatly appreciate any advice I can get.
PD. To make this post shorter I omitted a few details about what I did, if you need to know something I may have left out just ask in the comments.
Consider storing category's properties in a single list property prefixed with category property name.
Like (forget me I forgot exact Python syntax, switched to Go)
class Item():
props = StringListProperty()
book = Item(category='book', props=['title:Carl Sagan'])
button = Item(category='button', props=['wholes:5'])
Then you can do have a single composite index on category+props and do queries like this:
def filter_items(category, propName, propValue):
Item.filter(Item.category == category).filter(Item.props==propName+':'+propValue)
And you would need a function on Item to get property values cleaned up from prop names.

Django: variable parameters in URLconf

I've been looking for this question and couldn't find any, sorry if it's duplicated.
I'm building some kind of ecommerce site, similar to ebay. The problem i have arise when i'm trying to browse through "categories" and "filters". For example. You can browse the "Monitor" category. That will show you lots of monitors, and some filters (exactly the same as ebay) to apply them. So, you go to "monitors", then you have filters like:
Type: LCD - LED - CRT
Brand: ViewSonic - LG - Samsung
Max Resolution: 800x600 - 1024x768
And those filters will be appended to the URL, following with the example, when you browse monitors the URL could be something like:
store.com/monitors
If you apply the "Type" filter:
store.com/monitors/LCD
"Brand":
store.com/monitors/LCD/LG
"Max Resolution":
store.com/monitors/LCD/LG/1024x768
So, summarizing, the URL structure would be something like:
/category/filter1/filter2/filter3
I can't figure out how to do it really. The problem is that filters can be variable. I think in the view will need to use **kwargs but i'm not really sure.
Do you have any idea how to capture that kind of parameters?
Thanks a lot!
Ben, I hope this will help you
urls.py
from catalog.views import catalog_products_view
urlpatterns = patterns(
'',
url(r'^(?P<category>[\w-]+)/$', catalog_products_view, name="catalog_products_view"),
url(r'^(?P<category>[\w-]+)/(?P<filter1>[\w-]+)/$', catalog_products_view, name="catalog_products_view"),
url(r'^(?P<category>[\w-]+)/(?P<filter1>[\w-]+)/(?P<filter2>[\w-]+)/$', catalog_products_view, name="catalog_products_view"),
url(r'^(?P<category>[\w-]+)/(?P<filter1>[\w-]+)/(?P<filter2>[\w-]+)/(?P<filter3>[\w-]+)/$', catalog_products_view, name="catalog_products_view"),
)
view.py
def catalog_products_view(request, category, filter1=None, filter2=None, filter3=None):
# some code here
or
def catalog_products_view(request, category, **kwargs):
filter1 = kwargs['filter1']
filter2 = kwargs['filter2']
....
filterN = kwargs['filterN']
# some code here
You could add this to your urls:
url(r'^(?P<category>\w)/(?P<filters>.*)/$', 'myview'),
And then myview would get the parameters of category and filters. You could split filters on "/" and search for each part within the Filters table.
Does that make sense?
how do you intend to decide what aspect is being filtered by? Do you have a list of accepted keywords for each category? ie how does the server know that
/LCD/LG/
means type=LCD, brand=LG
but
/LG/LCD
doesn't mean type=LG, brand=LCD etc
Is there any reason you don't want to use GET params, e.g.
.../search/?make=LD&size=42

Django - filter ManyToManyField?

I'm not sure the best way to describe what it is that I'm trying to do so forgive my title.
I have two models, User and Group. Group contains field, members, which is a ManyToManyField referring to User.
Given a User, I want to find all of the Groups to which that user belongs.
My idea would be to do something like this:
groups = Group.objects.filter(user in members)
Something like that. Even though I realize that this isn't right
I tried reading through this link but couldn't figure out how to apply:
http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships
Thanks
EDIT:
Figured it out
groups = Group.objects.filter(members__username=user.username)
If you have the user and you want to have his groups then start querying from it, not the way around ;)
Here's an example:
james = User.objects.get(pk= 123)
james_groups = james.group_set.all()
The most concise way is probably
groups = user1.group_set.all()
which gives you a queryset that is iterable.

Categories