Group queryset by field - django

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)

Related

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;

alter the structure Tastypie uses in the list view

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.

Django rest framework CRUD API for model with foriegn key elements

Okay so here I am with another problem I'm facing with Django. This time it's the REST framework.
I have a Model with Foreign Key dependencies in my project. I had to retrieve the foreign key field as an object, not just an ID field and was successful in that using Serializer Relations.
So my Serializer.py looks like:
class EventSerializer(serializers.ModelSerializer):
owner = EventUserSerializer(read_only=False)
severity = EventSeveritySerializer(read_only=False)
type = EventTypeSerializer(read_only=False)
cause = EventCauseSerializer(read_only=False)
subcause = EventSubcauseSerializer(read_only=False)
impact = EventImpactSerializer(read_only=False)
point_location = PointLocationSerializer(read_only=False)
class Meta:
model = models.Event
fields = ('id', 'description', 'owner', 'status',
'severity', 'type', 'cause', 'subcause', 'impact',
'is_public', 'occurrence_time', 'reporting_agency',
'estimated_duration', 'confirmed_timestamp',
'rejected_timestamp', 'closed_timestamp', 'point_location', )
Making a GET request, I get the result I wanted:
{
"meta": {
"count": 1,
"previous": null,
"next": null
},
"results": [
{
"id": 8,
"description": "test event 1",
"owner": {
"user": {
"id": 1,
"username": "venus",
"email": "venus.saini#ibigroup.com"
}
},
"status": "confirmed",
"severity": {
"id": 2,
"created": "2016-08-24T07:27:24.722000Z",
"modified": "2016-08-24T07:27:24.723000Z",
"name": "Severe",
"is_enabled": true,
"sortorder": 1
},
"type": {
"id": 2,
"created": "2016-08-24T07:27:45.203000Z",
"modified": "2016-08-24T07:27:45.204000Z",
"name": "Accident",
"event_category": "unplanned",
"sortorder": 2
},
"cause": {
"id": 2,
"created": "2016-08-24T07:28:16.088000Z",
"modified": "2016-08-24T07:28:16.092000Z",
"name": "Whether Conditions",
"sortorder": 3,
"event_type": 2
},
"subcause": {
"id": 2,
"created": "2016-08-24T07:28:28.475000Z",
"modified": "2016-08-24T07:28:28.478000Z",
"name": "Slippery",
"display_name": "Slippery",
"sortorder": 4,
"cause": 2
},
"impact": {
"id": 2,
"created": "2016-08-24T07:28:40.599000Z",
"modified": "2016-08-24T07:28:40.599000Z",
"name": "All Lanes Blocked",
"sortorder": 5
},
"is_public": false,
"occurrence_time": "2016-08-25T06:34:13Z",
"reporting_agency": "",
"estimated_duration": null,
"confirmed_timestamp": "2016-08-25T06:34:15Z",
"rejected_timestamp": "2016-08-25T06:34:16Z",
"closed_timestamp": "2016-08-25T06:34:18Z",
"point_location": {
"id": 2,
"created": "2016-08-24T07:18:03.017000Z",
"modified": "2016-08-24T07:18:03.018000Z",
"roadway_name": "Northbound",
"direction": "North",
"is_primary": false,
"cross_street_name": "test street 1",
"offset": "After",
"distance": 3,
"is_forward": false
}
}]
}
The problem I face is while using the POST request. I don't know how that would work so I found this link. It looks like it has the solution; I mean this is exactly what I want to accomplish [passing the ID of the foreign key element makes the object entry]. But I keep getting random errors like super(BaseSerializer, self).__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'is_relation'.
Can somebody please guide me to how I should be doing it? I'm using Postman to test my APIs.
Thanks in advance.
EDIT: Using PUT/POST without the CustomSerializer gives me error 415:
{
"detail": "Unsupported media type \"text/plain;charset=UTF-8\" in request."
}

Does ember.js support segment-literal notation?

Ember.js doesnt seem to support json objects with dots in the objects attribute names (e.g.):
{ "ns1.id" : 14, "ns2.name" : "mike" };
Is this an omission or am i overlooking something? We have services that we are required to consume that support namespaces in this way.
Handlebars seems to support the above using segment-literal notation (e.g. {{[nd.id]}}). Is that also true of Ember? Is the documentation I have missed?
Thanks!
Yes you can do this. It is compound documents which is used to save HTTP requests, it may be convenient to send related documents along with the requested documents.
In this case, a bit of extra metadata for each relationship can link together the documents. Following example shows use of compound documents:
{
"rels": {
"posts.author": {
"url": "http://example.com/people/{post.author}",
"type": "people"
},
"posts.comments": {
"url": "http://example.com/comments/{post.comments}",
"type": "comments"
}
}
"posts": [{
"id": 1,
"title": "Rails is Omakase",
"rels": {
"author": 9,
"comments": [ 1, 2, 3 ]
}, {
"id": 2,
"title": "The Parley Letter",
"rels": {
"author": 9,
"comments": [ 4, 5 ]
}, {
"id": 1,
"title": "Dependency Injection is Not a Virtue",
"rels": {
"author": 9,
"comments": [ 6 ]
}
}],
"people": [{
"id": 9,
"name": "#d2h"
}],
"comments": [{
"id": 1,
"body": "Mmmmmakase"
}, {
"id": 2,
"body": "I prefer unagi"
}, {
"id": 3,
"body": "What's Omakase?"
}, {
"id": 4,
"body": "Parley is a discussion, especially one between enemies"
}, {
"id": 5,
"body": "The parsley letter"
}, {
"id": 6,
"body": "Dependency Injection is Not a Vice"
}]
}

django-piston: how to add an entity field to manyToMany related entity fields?

I have two Entities: Post and Tag, with a ManyToMany relation called 'tagged'
What I need to do, in order to parse json returned on particular client, is output fields by adding a field 'postID' (the pk field of current Post) to Tag related to that post.
So, my output now is:
{
"post": {
"name": "Dummy name",
"pk": 1,
"tags": [
{
"id": 2,
"name": "Patio"
},
{
"id": 3,
"name": "Roof"
}
],
"ref": "709230056"
}
},
but it should be:
{
"post": {
"name": "Dummy name",
"pk": 1,
"tags": [
{
"id": 2,
"name": "Patio",
"postID": 1,
},
{
"id": 3,
"name": "Roof"
"postID": 1,
}
],
"ref": "709230056"
}
},
I've alrady tried to play with fields of my Handler but with no success :(
How to do that ?
Thanks