Ember js for array binding - ember.js

I'm working on an application, where I am getting all categories through external api.
So now I need to get all subcategories for each category.
I have controller for that
CategoriesController = Ember.ArrayController.extend
#return all categories hits an api/categories
categories: (->
App.Category.find()
).property()
So now I need to get all subcategories for each category.
Basically we get subcategories from external api for each category.
so structure is
{"subcategories": [id: "1", name:"ss".. }
For this I have created another method to get subcategory for each category.
subcategories: ( ->
#get('categories').forEach (category) =>
##Get subcategories from external api
subcategories = App.Subcategory.find(category.id)
##making an array of objects
result = Ember.A()
result.pushObject({
category: categorys
subcategories: subcategories
)}
).property('#categories','#each')
so when I check subcategories it's always blank. What's wrong in it?
Thanks

Related

Django query in list view to group similar category records

I have my website which displays the records on website these records are of different categories how can group the records belongs to similar category and display them together
category 1
List item 1
List item 2
List item 3
class Mymixin:
def get_queryset(self):
return Record.objects.all()
class Model:
category = models.Charfield(max_length=255, choices=RecordsCategory.choices(True, True)
Just... order the records by category?
On how to do that: that depends on the nature of your website, which you didn't disclose, but at the end it will come to appending
queryset = queryset.order_by('category')
to whatever queryset is feeding the website. Not that you need to write this as is: how this should be written will differ greatly depending on your actual site technology.

Query haystack search with multiple URL params

I have my search working the way I need it to for the most part, but I would like to be able to sort based on the categories a user selects.
I have sub-classed searchForm to contain:
def no_query_found(self):
"""
Determines the behavior when no query was found.
By default, no results are returned (``EmptySearchQuerySet``).
Should you want to show all results, override this method in your
own ``SearchForm`` subclass and do ``return self.searchqueryset.all()``.
"""
return self.searchqueryset.models(Idea)
def search(self):
sqs = super(IdeaCategories, self).search()
if not self.is_valid():
return self.no_query_found()
if self.cleaned_data['category']:
sqs = sqs.filter(tags__contains=self.cleaned_data['category'])
return sqs
The following works as expected:
/testing/search/?q=test -> All results related to "test"
/testing/search/?category=Development&q= -> All results related to "development"
/testing/search/?category=Development&q=book -> All results related to "development" and containing "book"
The only thing I can't figure out is how to get it to search correctly on the categories of 2 or more:
/testing/search/?category=Development&category=Supplemental+Material&q=
Is there a way to get a list of categories, query and filter for combined results? Such as:
sqs = sqs.filter(tags__contains["Development", "Supplemental Material"])
Okay! So I got this figured out now.
Inside my searchForm class:
I created a list of choices from the database to use in a form.
choices_group = tuple(
[(choice, choice) for choice in
Category.objects.values_list('label', flat=True)])
Apply these choices to my form.
sort = forms.MultipleChoiceField(choices=choices_group, widget=forms.CheckboxSelectMultiple)
Created my query set.
q_sorted = self.cleaned_data['sort']
if q_sorted:
sqs = sqs.filter(tags__in=q_sorted)
Finally, in my template.
{{form.sort}}

How to 'join' a many-to-many 2 list of related Models

I have 2 models Product and Categories, with a many-to-many relation from Product to Category.
I have a list of Product objects and a list of Product ids.
Using the Product list ids, I get categories:
categories = Category.objects.filter(products__in=products_list)
Now I want to joint the products list and the categories, similar to a Prefetch, but I don't have a Queryset but a list of Product Objects.
for product in products # the list with Product objects
for category in categories:
if ...
ph.category = category
Being a many to many the relations are in the intermediary table, so I don't know how to access, not to do a new query for every category.
I'm thinking on somehow passing the "product_id" from intermediary table to category, in the Queryset.
Also I need only the first Category of each Product, not all of them.
I'd suggest you convert your product list into a queryset, and then use prefetch_related:
product_ids = [p.pk for p in products]
product_qs = Product.objects.filter(pk__in=product_ids).select_related('categories')
for product in product_qs:
product.categories.all() # This will be prefetched.

Django, Select related, Average, ManyToMany field

Suppose i have clients in my model (model Client), and suppose each client has a shopping cart (model Cart). Each cart has many items (model CartItems), then to finish, each item has a relation with one product (model Product).
Now, here goes my problem. I want to have the average of all shopping carts, which is based in the sum of all items of each cart, for each client. So i'll try to demonstrate you with more details below.
Try to imagine the directions of the relations like this:
Client->Cart->CartItems<-Product
Simplified description of each model:
Client (
id #pk
)
Cart (
id #pk
client_id #fk that references to Client.id
)
CartItems (
id #pk
cart_id #fk that references to Cart.id
product #fk that references to Product.id
)
ProductId (
id #pk
value # The price of the product
)
In pure SQL i've found the solution, and would be something like this query:
SELECT * FROM Client
INNER JOIN Cart ON Client.id = Cart.client_id
INNER JOIN
(SELECT AVG(c.total) AS average, cart_id FROM
(SELECT SUM(Product.price) AS total, CartItems.cart_id AS cart_id
FROM CartItems
INNER JOIN Product ON CartItems.product = Product.id
GROUP BY CartItems.cart_id) AS c GROUP BY c.cart_id) AS d
ON d.cart_id = Cart.id;
Anyone has any idea about how to convert this query to Django's model's patterns?
You sould do something like:
Cart.objects.values('client_id').annotate(cant=Sum('cart_id__product__value')).aggregate(Avg('cant'))
Notice that the annotations does not return a queryset, you should return the values.
Further reading: Aggregations in Django
My answer comes very late but I came accross this while searching for a solution to a similar issue.
In my case, I have a ManyToManyField relationship between the Cart and the CartItems, which made it fairly simple.
The models now look like this
Cart (
id #pk
client_id #fk that references to Client.id
items #manytomany relationship to CartItems
)
CartItems (
id #pk
product #fk that references to Product.id
)
To get the average for each cart, the query would just look like this
Cart.objects.annotate(carts_avg=Avg('items__product__value'))

Filtering queryset by boolean field on parent class

I'm not sure why this is causing me such a problem but I can't seem to get it figured out. I've got a CSV and PDF export for products in our Mezzanine / Cartridge product DB. It exports each ProductVariation in a row. Works great but I need to add a filter that exports only published products for instance. ProductVariations have a foreignkey relation to the Product model:
class ProductVariation(Priced):
"""
A combination of selected options from
``SHOP_OPTION_TYPE_CHOICES`` for a ``Product`` instance.
"""
product = models.ForeignKey("Product", related_name="variations")
The product model subclasses Displayable:
class Product(Displayable, Priced, RichText, AdminThumbMixin):
"""
Container model for a product that stores information common to
all of its variations such as the product's title and description.
"""
The Displayable class is used to determine whether a product is displayed for normal users or staff only:
CONTENT_STATUS_DRAFT = 1
CONTENT_STATUS_PUBLISHED = 2
CONTENT_STATUS_COMPLETE = 3
CONTENT_STATUS_INACTIVE = 4
CONTENT_STATUS_CHOICES = (
(CONTENT_STATUS_DRAFT, _("Draft")),
(CONTENT_STATUS_PUBLISHED, _("Online")),
(CONTENT_STATUS_COMPLETE, _("Complete")),
(CONTENT_STATUS_INACTIVE, _("Inactive")),
)
class Displayable(Slugged, MetaData, TimeStamped):
"""
Abstract model that provides features of a visible page on the
website such as publishing fields. Basis of Mezzanine pages,
blog posts, and Cartridge products.
"""
status = models.IntegerField(_("Status"),
choices=CONTENT_STATUS_CHOICES, default=CONTENT_STATUS_DRAFT,
help_text=_("The General public can only view content that has ONLINE status."))
In trying to filter the results by Status however I can't seem to get it to work the way I expect. In my report view I'll add something like this:
product_variations = ProductVariation.objects.filter('product__status' == 'CONTENT_STATUS_PUBLISHED')
but it just gives me an error that "'bool' object is not iterable". What am I doing wrong?
When you write:
ProductVariation.objects.filter('product__status' == 'CONTENT_STATUS_PUBLISHED')
The expression 'product__status' == 'CONTENT_STATUS_PUBLISHED' becomes a boolean.
Right syntax is:
ProductVariation.objects.filter(product__status = 'CONTENT_STATUS_PUBLISHED')