alter the structure Tastypie uses in the list view - django

I have json list view that look like this:
{
"objects": [
{
"active": false,
"id": 4,
},
{
"active": false,
"id": 5,
}
]
}
I want to get rid of "objects" word, so that structure will look like this:
{
[
{
"active": false,
"id": 4,
},
{
"active": false,
"id": 5,
}
]
}
This link to docs has no clue in it

It's impossible. {} means dict. Dict needs key and value.
I guess You need
[
{
"active": false,
"id": 4,
},
{
"active": false,
"id": 5,
}
]
If yes, overwrite Resource.alter_list_data_to_serialize function:
def alter_list_data_to_serialize(self, request, data):
return data[self._meta.collection_name]
Paginator class need to be dict with field named Resouce._meta.collection_name.

Related

Group queryset by field

I am working with Django and Django REST framework. I have a model called Selection that contains field called category, when i query the model to send the result to the frontend i get it with the following structure:
[
{
"id": 1,
"category": "SHOES",
"products": 122,
"created_at": "2021-09-11",
},
{
"id": 2,
"category": "SHOES",
"products": 4,
"created_at": "2021-10-07",
},
{
"id": 3,
"category": "CLOTHES",
"products": 0,
"created_at": "2021-10-08",
},
]
I need to put the selections of the same category in an array and remove the grouped-by category, like this:
{
"SHOES": [
{
"id": 1,
"products": 122,
"created_at": "2021-09-11",
},
{
"id": 2,
"products": 4,
"created_at": "2021-10-07",
}
],
"CLOTHES": [
{
"id": 3,
"category": "CLOTHES",
"products": 0,
"created_at": "2021-10-08",
}
]
}
I considered to making it with Javascript in the frontend, but before i wanted to know if there's a way to do this from Django.
Yes, you need to do some customisation in your code.
Get all categories by using values_list('category', flat=True) with your queryset
Iterate through them filtering category one by one
response_list = []
categories = Selection.objects.values_list('category', flat=True)
for category in categories:
data = Selection.objects.filter(category=category)
data = {
category: SelectionSerializer(data, many=True).data,
}
response_list.append(data)

Django Rest Framework pagination and filtering

Hi guys i am trying to make filtering with pagination but i cannot get the result i want.
This is my function in views.py.
class OyunlarList(generics.ListAPIView):
# queryset = Oyunlar.objects.all()
pagination_class = StandardPagesPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['categories__name', 'platform']
# serializer_class = OyunlarSerializer
def get_queryset(self):
queryset=Oyunlar.objects.all()
oyunlar=OyunlarSerializer.setup_eager_loading(queryset)
return oyunlar
def get(self,request,*args,**kwargs):
queryset = self.get_queryset()
serializer=OyunlarSerializer(queryset,many=True)
page=self.paginate_queryset(serializer.data)
return self.get_paginated_response(page)
This is my pagination class.
class StandardPagesPagination(PageNumberPagination):
page_size = 10
And this is the json i got but when i write localhost/api/games?platform=pc or localhost/api/games?categories=Action it is not working.
{
"count": 18105,
"next": "http://127.0.0.1:8000/api/oyunlar?categories__name=&page=2&platform=pc",
"previous": null,
"results": [
{
"game_id": 3,
"title": "The Savior's Gang",
"platform": "ps4",
"image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP3729-CUSA23817_00-THESAVIORSGANG00/1599234859000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000",
"categories": [],
"release_date": null
},
{
"game_id": 8,
"title": "Spellbreak",
"platform": "ps4",
"image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP0795-CUSA18527_00-SPELLBREAK000000/1599612713000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000",
"categories": [],
"release_date": null
},
{
"game_id": 11,
"title": "Marvel's Avengers",
"platform": "ps4",
"image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP0082-CUSA14030_00-BASEGAME0001SIEE/1599653581000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000",
"categories": [],
"release_date": null
},
{
"game_id": 24,
"title": "The Suicide of Rachel Foster",
"platform": "ps4",
"image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP8923-CUSA19152_00-DAEEUTSORF000001/1599610166000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000",
"categories": [
{
"category_id": 2,
"name": "Casual"
},
{
"category_id": 5,
"name": "İndie"
},
{
"category_id": 8,
"name": "Adventure"
}
],
"release_date": "2020-09-09"
},
{
"game_id": 25,
"title": "Takotan",
"platform": "ps4",
"image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP2005-CUSA24716_00-TKTN000000000000/1599610166000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000",
"categories": [
{
"category_id": 1,
"name": "Action"
},
{
"category_id": 12,
"name": "Arcade"
},
{
"category_id": 13,
"name": "Shooter"
}
],
"release_date": "2020-09-09"...
Can you help me guys with this problem?I couldn't find any solution.
If you override the get method you have to make sure you know how the original implementation looks like.
def get(self,request,*args,**kwargs):
queryset = self.filter_queryset(self.get_queryset())
...
So filter_queryset is the missing piece here.

how to get records with its related data in intermediate table

I have two model, Category and Brand with many to many relation
in Category model
public function brands()
{
return $this->belongsToMany(Brand::class, 'brand_category', 'category_id', 'brand_id');
}
and in brand model
public function categories()
{
return $this->belongsToMany(Category::class, 'brand_category','brand_id','category_id' );
}
how can i get brands with specific category id like json below
{
"data": [
{
"brand_id": 1,
"name": "Sony",
"description": null,
"logo": null,
"is_active": true,
"created_at": "2020-04-08 15:19:44",
"updated_at": "2020-04-08 15:19:44",
"deleted_at": null,
"pivot": {
"category_id": 1,
"brand_id": 1
}
},
{
"brand_id": 2,
"name": "Lg",
"description": null,
"logo": null,
"is_active": true,
"created_at": "2020-04-08 15:19:44",
"updated_at": "2020-04-08 15:19:44",
"deleted_at": null,
"pivot": {
"category_id": 1,
"brand_id": 2
}
}
],
"success": true,
"error": {
"code": 200,
"data": []
},
"message": ""
}
i want to find a way without changing relations in models by wherePivot...
this should do.
return Category::find($categoryId)->brands;

Elasticsearch template not reading params

I've been following the example at this site Parameterizing Queries in Solr and Elasticsearch in the ES section. Note, it is an older ES version that the author is working with, but I don't think that should affect this situation. I am using version 1.6 of ES.
I have a template {{ES_HOME}}/config/scripts/test.mustache that looks like the below snippet. Note the {{q}} parameter in "query".
{
"query": {
"multi_match": {
"query": "{{q}}",
"analyzer": "keyword",
"fields": [
"description^10",
"name^50",
]
}
},
"aggregations": {
"doctype" : {
"terms" : {
"field" : "doctype.untouched"
}
}
}
}
I POST to http://localhost:9200/forward/_search/template with the following message body
{
"template": {
"file": "test",
"params": {
"q": "a"
}
}
}
It runs the template, but gets 0 hits, and returns the following:
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 0,
"max_score": null,
"hits": []
},
"aggregations": {
"doctype": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": []
},
}
}
Alternatively, if I hard code "a" into where {{q}} is, and post to the template, it correctly returns results for the query "a". Am I doing something inherently wrong in my design?
According to the docs, the params object should be outside of the template object
{
"template": {
"file": "test"
},
"params": {
"q": "a"
}
}

Retrieving specif fields from nested object returned by elasticsearch

I am new to elasticsearch. I am trying to retrieve the selected fields from nested object returned by elasticsearch. Below is the object stored in elasticsearch index:
{
"_index": "xxx",
"_type": "user",
"_id": "2",
"_version": 1,
"exists": true,
"_source": {
"user": {
"user_auth": {
"username": "nickcoolster#gmail.com",
"first_name": "",
"last_name": "",
"is_active": false,
"_state": {
"adding": false,
"db": "default"
},
"id": 2,
"is_superuser": false,
"is_staff": false,
"last_login": "2012-07-10 21:11:53",
"password": "sha1$a6caa$cba2f821678ccddc4d70c8bf0c8e0655ab5c279b",
"email": "nickcoolster#gmail.com",
"date_joined": "2012-07-10 21:11:53"
},
"user_account": {},
"user_profile": {
"username": null,
"user_id": 2,
"following_count": 0,
"sqwag_count": 0,
"pwd_reset_key": null,
"_state": {
"adding": false,
"db": "default"
},
"personal_message": null,
"followed_by_count": 0,
"displayname": "nikhil11",
"fullname": "nikhil11",
"sqwag_image_url": null,
"id": 27,
"sqwag_cover_image_url": null
}
}
}
}
Now I want only certain fields to be returned from user.user_auth(like password,superuser etc should not be returned).
I am using django PyES and below is the code that i tried:
fields = ["user.user_auth.username","user.user_auth.first_name","user.user_auth.last_name","user.user_auth.email"]
result = con.search(query=q,indices="xxx",doc_types="user",fields=fields)
but the result that I get is only email being retrieved (i:e only last field being returned):
{
"user.user_auth.email": "nikhiltyagi.eng#gmail.com"
}
I want this abstraction for both the nested objects (i:e user_auth,user_profile)
how do I do this?
What about using latest django-haystack? It covers also ElasticSearch as a backend so you can get well binded ElasticSearch FTS to your project.