Tastypie filter by minimum value - backbone.js

I have a Django-tastypie resource that represents a banner and has a field called impression that I increment whenever the banner appears on the site.
class BannerResource(ModelResource):
owner = fields.ForeignKey('advertisment.api.AdvertiserResource', 'owner', full=True)
class Meta:
queryset = Banner.objects.all()
resource_name = 'banner'
authorization = Authorization()
I would like to get the banner that has the minimum impression, in the official documentation there is nothing like
filtering = {'impressions': ('min',)}
I'm using BackboneJS in the front end and I could get all the banners with Backbone collection and do the filtering with JavaScript but I'm looking for a quicker way to do it.
Any ideas?
Thanks

If you'd like to retrieve banners with number of impressions greater than X you need to things. For one you need to define possible filtering operations on your resource like so (given your model has impressions field):
class BannerResource(ModelResource):
owner = fields.ForeignKey('advertisment.api.AdvertiserResource', 'owner', full=True)
class Meta:
queryset = Banner.objects.all()
resource_name = 'banner'
authorization = Authorization()
filtering = { 'impressions' : ALL }
for available options take a look at Tastypie's documentation on filtering.
Then if you made the following request:
GET http://<your_host>/v1/banners?impressions__gte=X
you should get what you need.

Related

How can i filter a Product by price in DRF

I have a model class Products in which I simple specify product-URL, product-title and product-price as attributes. and make Serializer.py file use ModelSerializer and pass data to Reactjs Now I can't understand that how can i filter products by there price so if I fetch API in react all High price are sorted first or low after according to user need or our option...thanks
There are multiple ways you can do this:
1. Using DRF Filter Backends:
DRF Filtering Documentation - Ordering
Based on the official DRF documentation, you need to specify your filter backends in your settings or your view like so:
from rest_framework import filters
class ProductListView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = ProductSerializer
filter_backends = [filters.OrderingFilter]
ordering_fields = ['price']
You're going to be able to filter your list with a request parameter:
http://example.com/api/products?ordering=price
Or reverse ordering by:
http://example.com/api/products?ordering=-price
2. hardcoding the sorting in your queryset
class ProductListView(generics.ListAPIView):
queryset = User.objects.all().order_by('-score')
serializer_class = ProductSerializer
Basically, you don't want to hardcode your ordering unless you are always sure you want the results to be ordered that way. Otherwise, filter backends are the way to go.

Filtering on PageQuerySet (which is retuned by specific()) is returning FieldError in Wagtail

I am using subclassed model of Wagtail Page.
In below code you can see that PhoenixPage is base page which subclasses Wagtail Page model.
PhoenixArticlePage & PhoenixMealPrepPage subclasses PhoenixPage
PhoenixArticleIndexPage subclasses PhoenixBaseIndexPage which in turn subclasses PhoenixPage
Idea is to use PhoenixArticleIndexPage for all other article pages.
Problem is even after using the specific() method on queryset i am unable to use filter or any other operation on the queryset.
i tried using order_by() as well as filter()
Can someone share some insights here ? what might be wrong ?
Here is a model example:
class PhoenixPage(Page):
"""
General use page with caching, templating, and SEO functionality.
All pages should inherit from this.
"""
class Meta:
verbose_name = _("Phoenix Page")
# Do not allow this page type to be created in wagtail admin
is_creatable = False
tags = ClusterTaggableManager(
through=PhoenixBaseTag,
verbose_name="Tags",
blank=True,
related_name="phoenixpage_tags",
)
class PhoenixBaseIndexPage(PaginatedListPageMixin, PhoenixPage):
class meta:
verbose_name = "Phoenix Base Index Page"
app_label = "v1"
index_show_subpages_default = True
is_creatable = False
class PhoenixArticleIndexPage(PhoenixBaseIndexPage):
class Meta:
verbose_name = "Phoenix Article Index Page"
app_label = "v1"
class PhoenixArticlePage(PhoenixPage):
class Meta:
verbose_name = "Phoenix Article Page"
app_label = "v1"
subpage_types = []
parent_page_types = ["v1.PhoenixArticleIndexPage"]
class PhoenixMealPrepPage(PhoenixPage):
class Meta:
verbose_name = "Phoenix Meal Prep Page"
app_label = "v1"
subpage_types = []
parent_page_types = ["v1.PhoenixArticleIndexPage"]
Here are shell queries i tried.
Index page
In [4]: a = PhoenixArticleIndexPage.objects.all()[0]
In [5]: a
Out[5]: <PhoenixArticleIndexPage: articles>
As expected, get_children returning all instances of Wagtail Page.
In [6]: a.get_children()
Out[6]: <PageQuerySet [<Page: article title>, <Page: article title2>, <Page: Our 30-Day Reset Recipes Are So Easy AND Delicious>]>
Getting specific children from the Index page.
In [7]: a.get_children().specific()
Out[7]: <PageQuerySet [<PhoenixArticlePage: article title>, <PhoenixArticlePage: article title2>, <PhoenixMealPrepPage: Our 30-Day Reset Recipes Are So Easy AND Delicious>]>
Get Tag and try to filter the queryset
In [8]: q = a.get_children().specific()
In [12]: m = PhoenixTag.objects.get(slug='meal')
In [16]: k={"tags":m}
In [19]: q.filter(**k)
***FieldError: Cannot resolve keyword 'tags' into field. Choices are ...***
But if i go to particular entry in queryset then i can see tags field on it.
In [15]: q[2]
Out[15]: <PhoenixMealPrepPage: Our 30-Day Reset Recipes Are So Easy AND Delicious>
In [16]: q[2].tags
Out[16]: <modelcluster.contrib.taggit._ClusterTaggableManager at 0x1060832b0>
Could be different question all together but for reference adding it here.
Found the corner case of using difference() and specific() method on a queryset.
In [87]: q = PhoenixPage.objects.child_of(a).live()
In [89]: f = q.filter(featured=True)[:3]
In [91]: l = q.difference(f)
In [93]: l.order_by(a.index_order_by).specific() . <-- does not work
DatabaseError: ORDER BY term does not match any column in the result set.
The specific() method on PageQuerySet works by running the initial query on the basic Page model as normal, then running additional queries - one for each distinct page type found in the results - to retrieve the information from the specific page models. This means it's not possible to use fields from the specific model in filter or order_by clauses, because those have to be part of the initial query, and at that point Django has no way to know which page models are involved.
However, if you know that your query should only ever return pages of one particular type (PhoenixPage in this case) containing the field you want to filter/order on, you can reorganise your query expression so that the query happens on that model instead:
PhoenixPage.objects.child_of(a).filter(tags=m).specific()

Get orderable fields - Django Rest

I have a ReactJS table that uses fetch API to get the data from a Django server using Rest. I've defined the viewset to use OrderingFilter and specified the ordering_fields as so:
class RecipientViewSet(BaseViewSetClass):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.RecipientsSerializer
filter_backends = (filters.OrderingFilter,)
ordering_fields = (
'id',
'externalID',
'firstname',
'lastname',
)
It works great, but I want to know if there's a method of getting from the ordering_fields from the server with fetch, so that I can add a sort icon only for the table headers that can be used to set the data's ordering.
I should add that in the Django REST Framework GUI I can click "Filters" button and view all possible filters for this viewset, and that's exactly what I want to get with ReactJS.
Thanks for any help!
I don't think there is a way to get the ordering fields out of the box via an API call, but you can always add an endpoint to return them:
from rest_framework import viewsets
from rest_framework.decorators import list_route
class MyViewSet(viewsets.GenericViewSet):
ordering_fields = ('a', 'b')
#list_route
def get_ordering_fields(self, request):
return self.ordering_fields
This way calling /your_endpoint/get_ordering_fields/ will return the list of ordering fields defined in the class. You can apply any formatting before returning them if you wish.
Also keep in mind that this behavior can be implemented in a base or mixin class so it can be reused easily later.
See the docs about list and detail routes.

Google App Engine + Validation

I am looking for how to do validation on Google App Engine and I have found only how to do it using Django framework. Ok Django approach is ok but if I have one form and this form have data from few tables what then???
I can not do it like this:
class Item(db.Model):
name = db.StringProperty()
quantity = db.IntegerProperty(default=1)
target_price = db.FloatProperty()
priority = db.StringProperty(default='Medium',choices=[
'High', 'Medium', 'Low'])
entry_time = db.DateTimeProperty(auto_now_add=True)
added_by = db.UserProperty()
class ItemForm(djangoforms.ModelForm):
class Meta:
model = Item
exclude = ['added_by']
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>'
'<form method="POST" '
'action="/">'
'<table>')
# This generates our shopping list form and writes it in the response
self.response.out.write(ItemForm())
self.response.out.write('</table>'
'<input type="submit">'
'</form></body></html>')
def post(self):
data = ItemForm(data=self.request.POST)
if data.is_valid():
# Save the data, and redirect to the view page
entity = data.save(commit=False)
entity.added_by = users.get_current_user()
entity.put()
self.redirect('/items.html')
else:
# Reprint the form
self.response.out.write('<html><body>'
'<form method="POST" '
'action="/">'
'<table>')
self.response.out.write(data)
self.response.out.write('</table>'
'<input type="submit">'
'</form></body></html>')
Is any easy way to validate form which contain data from few tables or I have to code it alone?
Looks like you're using webapp; I suggest your look at some other 'light-weight' choices for form validation. Pick one that you like the layout / syntax of. You'll be able to define complex 'nested' relationships if needed.
FormEncode
Formish
Deform
WTForms has a GAE component WTForms
WTForms now includes support for AppEngine fields as well as auto-form generation. The form class can be used as it is or serve as a base for extended form classes, which can then mix non-model related fields, subforms with other model forms, among other possibilities.

django model/modelForm - How to get dynamic choices in choiceField?

i'm experimenting with django and the builtin admin interface.
I basically want to have a field that is a drop down in the admin UI. The drop down choices should be all the directories available in a specified directory.
If i define a field like this:
test_folder_list = models.FilePathField(path=/some/file/path)
it shows me all the files in the directory, but not the directories.
Does anyone know how i can display the folders?
also i tried doing
test_folder_list = models.charField(max_length=100, choices=SOME_LIST)
where SOME_LIST is a list i populate using some custom code to read the folders in a directory. This works but it doesn't refresh. i.e. the choice list is limited to a snapshot of whatever was there when running the app for the first time.
thanks in advance.
update:
after some thinking and research i discovered what i want may be to either
1. create my own widget that is based on forms.ChoiceField
or
2. pass my list of folders to the choice list when it is rendered to the client
for 1. i tried a custom widget.
my model looks like
class Test1(models.Model):
test_folder_ddl = models.CharField(max_length=100)
then this is my custom widget:
class FolderListDropDown(forms.Select):
def __init__(self, attrs=None, target_path):
target_folder = '/some/file/path'
dir_contents = os.listdir(target_folder)
directories = []
for item in dir_contents:
if os.path.isdir(''.join((target_folder,item,))):
directories.append((item, item),)
folder_list = tuple(directories)
super(FolderListDropDown, self).__init__(attrs=attrs, choices=folder_list)
then i did this in my modelForm
class test1Form(ModelForm):
test_folder_ddl = forms.CharField(widget=FolderListDropDown())
and it didn't seem to work.What i mean by that is django didn't want to use my widget and instead rendered the default textinput you get when you use a CharField.
for 2. I tried this in my ModelForm
class test1Form(ModelForm):
test_folder_ddl = forms.CharField(widget=FolderListDropDown())
test_folder_ddl.choices = {some list}
I also tried
class test1Form(ModelForm):
test_folder_ddl = forms.ChoiceField(choices={some list})
and it would still render the default char field widget.
Anyone know what i'm doing wrong?
Yay solved. after beating my head all day and going through all sorts of examples by people i got this to work.
basically i had the right idea with #2. The steps are
- Create a ModelForm of our model
- override the default form field user for a models.CharField. i.e. we want to explcitly say use a choiceField.
- Then we have to override how the form is instantiated so that we call the thing we want to use to generate our dynamic list of choices
- then in our ModelAdmin make sure we explicitly tell the admin to use our ModelForm
class Test1(models.Model):
test_folder_ddl = models.CharField(max_length=100)
class Test1Form(ModelForm):
test_folder_ddl = forms.choiceField()
def __init__(self, *args, **kwargs):
super(Test1Form, self).__init__(*args, **kwargs)
self.fields['test_folder_ddl'].choices = utility.get_folder_list()
class Test1Admin(admin.ModelAdmin):
form = Test1Form
I use a generator:
see git://gist.github.com/1118279.git
import pysvn
class SVNChoices(DynamicChoice):
"""
Generate a choice from somes files in a svn repo
""""
SVNPATH = 'http://xxxxx.com/svn/project/trunk/choices/'
def generate(self):
def get_login( realm, username, may_save ):
return True, 'XXX', 'xxxxx', True
client = pysvn.Client()
client.callback_get_login = get_login
return [os.path.basename(sql[0].repos_path) for sql in client.list(self.SVNPATH)[1:]]

Resources