how to get records with its related data in intermediate table - postman

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;

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)

SSRS Subscription using REST API

Can we create/modify SSRS Subscription using REST API as SQL Server Reporting services 2017 supports REST API calls?
here is an online swagger example they built, but some properties are invalid or missing. Ex: Schedule property is missing and ExtensionSettings.ParameterValues is an array instead of an object
https://app.swaggerhub.com/apis/microsoft-rs/SSRS/2.0#/Subscriptions/GetSubscriptions
here is an example of a body message that works for me when posting:
{ "DataQuery": null, "DeliveryExtension": "Report Server Email", "Description": "test3", "EventType": "TimedSubscription", "ExtensionSettings": { "Extension": "Report Server Email", "ParameterValues": [ { "IsValueFieldReference": false, "Name": "TO", "Value": "userName" }, { "IsValueFieldReference": false, "Name": "IncludeReport", "Value": "True" }, { "IsValueFieldReference": false, "Name": "RenderFormat", "Value": "PDF" }, { "IsValueFieldReference": false, "Name": "Subject", "Value": "#ReportName was executed at #ExecutionTime" }, { "IsValueFieldReference": false, "Name": "IncludeLink", "Value": "True" }, { "IsValueFieldReference": false, "Name": "Priority", "Value": "NORMAL" } ] }, "IsActive": true, "IsDataDriven": false, "LastRunTime": null, "LastStatus": "New Subscription", "LocalizedDeliveryExtensionName": "E-Mail", "ModifiedBy": "userName", "ModifiedDate": "2020-09-04T13:45:51.343-05:00", "Owner": "userName", "ParameterValues": [], "Report": "/Folder Name/Report Name", "Schedule": { "Definition": { "EndDate": "0001-01-01T00:00:00Z", "EndDateSpecified": false, "Recurrence": { "DailyRecurrence": { "DaysInterval": 1 }, "MinuteRecurrence": null, "MonthlyDOWRecurrence": null, "MonthlyRecurrence": null, "WeeklyRecurrence": null }, "StartDateTime": "2020-09-04T02:00:00-05:00" }, "ScheduleID": null }, "ScheduleDescription": "At 2:00 AM every day, starting 9/4/2020" }

multiple relations using same model type in ember data

I have an account model that has the following:
export default Model.extend({
primaryStaff: belongsTo('staff'),
secondaryStaff: belongsTo('staff')
});
primaryStaff maps to the primaryStaffId key on the account model and secondaryStaff maps to secondaryStaffId. Is there a way to allow these to both point to the staff model?
Not having any luck. Thanks!
Update:
I'm using the JSON API Adapter -- here's a sample payload:
{
"data": {
"type": "account",
"id": "17",
"attributes": {
"businessId": 1,
"userId": 22,
"scopes": [
"customer",
"customer-22"
],
"keyCode": null,
"lockboxCode": null,
"notes": null,
"active": false,
"createdAt": "2017-01-31T20:13:39.465Z",
"updatedAt": "2017-02-20T03:49:17.308Z",
},
"relationships": {
"business": {
"data": {
"type": "business",
"id": "1"
}
},
"customer": {
"data": {
"type": "customer",
"id": "22"
}
},
"secondaryStaff": {
"data": null
},
"primaryStaff": {
"data": {
"type": "staff",
"id": "1"
}
}
}
}
}
You need to modify application (or model) serializer.
Please take a look at this twiddle

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

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.