How to set dynamic attributes in django rest framework serializers? - django

I have some json in the following format:
{
"daySchedules": {
"500000004061582000": {
"scheduleName": "Friday-Sunday",
"services": [
{
"name": "Lunch",
"hours": {
"startTime": "12:00:00.000",
"endTime": "16:00:00.000"
},
"overnight": false
},
{
"name": "Dinner",
"hours": {
"startTime": "17:00:00.000",
"endTime": "23:00:00.000"
},
"overnight": false
}
],
"openTime": "12:00:00.000",
"closeTime": "23:00:00.000"
},
"500000004061559163": {
"scheduleName": "Tuesday-Thursday",
"services": [
{
"name": "Breakfast",
"hours": {
"startTime": "04:00:00.000",
"endTime": "11:00:00.000"
},
"overnight": false
},
{
"name": "Lunch",
"hours": {
"startTime": "12:00:00.000",
"endTime": "16:00:00.000"
},
"overnight": false
},
{
"name": "Dinner",
"hours": {
"startTime": "17:00:00.000",
"endTime": "20:00:00.000"
},
"overnight": false
}
],
"openTime": "04:00:00.000",
"closeTime": "20:00:00.000"
}
},
"weekSchedule": {
"monday": null,
"tuesday": "500000004061559163",
"wednesday": "500000004061559163",
"thursday": "500000004061559163",
"friday": "500000004061582000",
"saturday": "500000004061582000",
"sunday": "500000004061582000"
}
}
The attributes in the json 500000004061582000 and 500000004061559163 is dynamic and determined by what's returned in the weekSchedule.
I wish to create the following serializers:
class ScheduleForDaySerializer(serializers.Serializer):
schedule_name = serializers.CharField()
services = serializers.ListField()
open_time = serializers.CharField()
close_time = serializers.CharField()
class WeekScheduleSerializer(serializers.Serializer):
monday = serializers.CharField(allow_null=True)
tuesday = serializers.CharField(allow_null=True)
wednesday = serializers.CharField(allow_null=True)
thursday = serializers.CharField(allow_null=True)
friday = serializers.CharField(allow_null=True)
saturday = serializers.CharField(allow_null=True)
sunday = serializers.CharField(allow_null=True)
class DaySchedulesSerializer(serializers.Serializer):
# what comes here?
class SchedulesSerializer(serializers.Serializer):
day_schedules = DaySchedulesSerializer()
week_schedule = WeekScheduleSerializer()
I'm struggling to determine how to serialize the attributes for that daySchedules json object since the key attributes are dynamic and not necessarily the same each time. Ideally I want to explicitly list out what each attribute type is.
After creating the serializer I want to do the following:
serializer = SchedulesSerializer(data=data) # data is the json object shown above
serializer.is_valid()
response = serializer.data
# do something with the response

Related

How to change DRF API SlugRelatedField Response template

I have managed to create a working model with 2 different serializers, depending on what we are doing. Right now, ReadTitleSerializer returns the below JSON object:
[
{
"id": 1,
"category": {
"id": 1,
"name": "Movies",
"slug": "movie"
},
"genres": [
{
"id": 1,
"name": "Drama",
"slug": "drama"
}
],
"name": "Drama Llama",
"year": "1998-02-02",
"description": null,
"rating": null
}
]
And this is the response from WriteTitleSerializer:
{
"id": 1,
"category": "movie",
"genres": [
"drama"
],
"name": "Drama Llama",
"year": "1998-02-02",
"description": null,
"rating": null
}
How can I make WriteTitleSerializer respond similarly to ReadTitleSerializer? I am using SlugRelatedField in WriteTitleSerializer because the JSON input should be a list of slugs.
Input JSON
{
"name": "Drama Llama",
"year": "1998-02-02",
"category": "movie",
"genres": [
"drama"
]
}
serializers.py
class ReadTitleSerializer(serializers.ModelSerializer):
category = CategorySerializer()
genres = GenreSerializer(many=True)
class Meta:
model = Title
fields = '__all__'
read_only_fields = ('category', 'genres')
class WriteTitleSerializer(serializers.ModelSerializer):
category = SlugRelatedField(
slug_field='slug',
queryset=Category.objects.all(),
required=True
)
genres = SlugRelatedField(
slug_field='slug',
queryset=Genre.objects.all(),
many=True,
required=True
)
class Meta:
model = Title
fields = '__all__'

Power Query M. Json array of key-pair transform in Column

Thanks for your help,
I'm trying to transform the Array called 'Tags' hosting a list of pair of key-values into a list of columns: CustomerId, CustomerDisplayName, CustomerPath where each list contains a respective value being a store for each charge.
{
"periodFrom": "2020-11-09T00:00:00",
"periodTo": "2020-12-08T00:00:00",
"charges": [
{
"listPrice": 5.05,
"netPrice": 5.05,
"netPriceProrated": 5.05,
"subTotal": 5.05,
"currency": "CAD",
"isBilled": true,
"isProratable": true,
"deductions": [],
"fees": [],
"invoice": {
"number": "2822835",
"date": "2020-11-16T00:00:00",
"periodFrom": "2020-10-09T00:00:00",
"periodTo": "2020-11-08T00:00:00"
},
"taxes": [
{
"name": "GST",
"appliedRate": 5.0
},
{
"name": "QST",
"appliedRate": 9.975
}
],
"tags": [
{
"name": "CustomerId",
"value": "42c8edf4-365a-4068-bde6-33675832afbb"
},
{
"name": "CustomerDisplayName",
"value": "Blue Sky Group"
},
{
"name": "CustomerPath",
"value": "Devmesh Co-Branded/Blue Sky Group"
}
]
}
]
}
Here the actual snippet of code I'm actually
let
...
Response2 = Table.FromRecords( { Response } ),
#"Expand1" = Table.ExpandListColumn(Response2, "charges"),
#"Expand2" = Table.ExpandRecordColumn(#"Expand1", "charges", {"productId", "productName", "sku", "chargeId", "chargeName", "chargeType", "periodFrom", "periodTo", "quantity", "listPrice", "netPrice", "netPriceProrated", "subTotal", "currency", "isBilled", "isProratable", "deductions", "fees", "invoice", "taxes", "tags"}, {"charges.productId", "charges.productName", "charges.sku", "charges.chargeId", "charges.chargeName", "charges.chargeType", "charges.periodFrom", "charges.periodTo", "charges.quantity", "charges.listPrice", "charges.netPrice", "charges.netPriceProrated", "charges.subTotal", "charges.currency", "charges.isBilled", "charges.isProratable", "charges.deductions", "charges.fees", "charges.invoice", "charges.taxes", "charges.tags"})
in
#"Expand2"

queryset filtering via a list of query values

A beginner django question...
Here's a JSON response...
"data": [
{
"type": "Subject",
"id": "0",
"attributes": {
"created": "2019-01-01T00:00:00Z",
"modified": "2019-01-01T00:00:00Z",
"subject_code": "A&H",
"subject_name": "AH",
"subject_short_name": "A & HUM"
},
"relationships": {
"organization": {
"data": {
"type": "Organization",
"id": "61"
}
},
"created_user": {
"data": null
},
"last_updated_user": {
"data": null
}
},
"links": {
"self": "http://localhost:8001/v1/subject_owner/0"
}
},
The above response is coming from a serializer
queryset = Subject.objects.all()
I have a query which is
http://localhost:8001/v1/subject_owner?owner_ids=62,63
So, how do we write a filtering condition for the owner_ids as a list? The response should have only the results where the owner_ids match organization_id. I have tried few:
queryset.filter(organization__in=[owner_id_list])
and
queryset.filter(organization=owner_id_list)
and obviously they don't work. Any help will be appreciated.
FYI, here's the model class...
class SubjectManager(models.Manager):
def get_by_natural_key(self, subject_code):
return self.get(subject_code=subject_code)
class Subject(get_subject_base_class(Organization)):
objects = SubjectManager()
def __str__(self):
return self.subject_code
def natural_key(self):
return (self.subject_code,)
You have to make something like that:
owner_id_list = [62, 63]
Subject.objects.filter(organization_id__in=owner_id_list)

Flask restless - A search filter for a relationship.property != val in case of one-to-many relationship

Flask-sqlalchemy Models for my book and actions tables are
class Book(db.Model):
__tablename__ = 'book'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
activity = db.relationship('Actions')
class Actions(db.Model):
__tablename__ = 'actions'
id = db.Column(db.Integer, primary_key=True)
book_id = db.Column(db.Integer, db.ForeignKey('book.id'), nullable=False)
action = db.Column(db.Enum(['requested', 'issued', 'opened', 'closed']), nullable=True)
created_on = db.Column(db.DateTime, default=_get_date_time)
Basically it's a one-to-many relationship between a book and actions. And I am using flask-restless for the API.
I need to get
All books that have not been closed
I have tried below search queries
q={
"filters": [
{
"name": "activity",
"op": "any",
"val": {
"name": "action",
"op": "not_equal_to",
"val": "closed"
}
}
]
}
and
q={
"filters": [
{
"name": "activity",
"op": "any",
"val": {
"name": "action",
"op": "not_in",
"val": ["closed"]
}
}
]
}
But I am getting wrong result
{
"num_results": 30,
"objects": [
{
"activity": [
{
"action": "opened",
"created_on": "2015-06-05T17:05:07",
"id": 31
},
{
"action": "closed",
"created_on": "2015-06-05T17:05:44",
"id": 32
}
],
"id": 1,
"name": "K&R"
....
},
...
]
"page": 1,
"total_pages": 3
}
Am I making some mistake here or this kind of thing is not possible in restless?
Please help me out.
Try this:
q = { "filters":[
{
"name":"activity__action",
"op":"not_equal_to",
"val":"closed"
}
]
}

How to nest a serializer?

So I'm trying to create an /api/info url that return various data on my application. It pulls data from various models and puts it together in one response. I got the following:
class SessionInfo(generics.GenericAPIView):
def get(self, request, format=None):
token = Token.objects.get(user=self.request.user)
userprofile = UserProfile.objects.get(user=self.request.user)
is_admin = self.request.user.is_staff
is_primary_owner = userprofile.primary_owner
managers = userprofile.reports_to.all()
man = ["test manager 1", "test manager 2"]
pages = Page.objects.filter(published=True, show_in_menu=True)
pages_output = JSONRenderer().render(PageSerializer(pages).data)
content = {
'user': {
"username": str(self.request.user.username),
"first_name": str(self.request.user.first_name),
"last_name": str(self.request.user.last_name),
"is_admin": is_admin,
"is_primary_owner": is_primary_owner,
"api_token": token.key,
"timezone": 'blalala',
"managers": man,
},
'license': {
"plan" : "gold",
"expiry_date" : "lol",
},
'feature_flags': {
'billing_test': False,
},
'pages': { pages_output },
}
return Response(content)
However it doesn't properly serialize and render pages, making it an escaped string instead:
{
"feature_flags": {
"billing_test": false
},
"user": {
"username": "test#user.com",
"first_name": "Test",
"last_name": "User",
"is_admin": true,
"managers": [
"test manager 1",
"test manager 2"
],
"api_token": "08d1a5827da9a90e7746949ffd2e69e87c51b272",
"timezone": "blalala",
"is_primary_owner": false
},
"license": {
"expiry_date": "lol",
"plan": "gold"
},
"pages": [
"[{\"id\": 1, \"title\": \"Trololol\"}, {\"id\": 2, \"title\": \"NEW pages\"}]"
]
}
if I use directuly use pages_output = PageSerializer(pages) I get:
<webapp_api_v1.serializers.PageSerializer object at 0x10a0d8f90> is not JSON serializable
How can I make a serializer properly nest within my constructed response? Thanks!
Solved it with pages_output = PageSerializer(pages).data and changing 'pages': pages_output,