Django rest framework CRUD API for model with foriegn key elements - django

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."
}

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)

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;

can we retrieve the data by sending id field as json object using POST method in django rest framework

GET : http://127.0.0.1:8000/r/
{
"count": 5,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"url": "http://127.0.0.1:8000/r/1/",
"name": "India",
"code": 91
},
{
"id": 2,
"url": "http://127.0.0.1:8000/r/3/",
"name": "us",
"code": 10,
},
{
"id": 3,
"url": "http://127.0.0.1:8000/r/4/",
"name": "pak",
"code": 9
},
{
"id": 4,
"url": "http://127.0.0.1:8000/r/5/",
"name": "kansas",
"code": 44
},
{
"id": 5,
"url": "http://127.0.0.1:8000/r/6/",
"name": "kanada",
"code": 123
}
}
I know that , suppose I can get "name": "us", "code": 10 based on it's "id": 2 by specifying the id in the URL like http://127.0.0.1:8000/r/2,
By using GET method,
but I want to retrive "name": "us", "code": 10 based on it's "id": 2 by sending it(means 'id') as json object using 'POST' method.

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.

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