Marshaling items in lists using flask restful - flask

I am writing a Flask-RESTFUL resource. It returns a Model object called DocumentSet with the following structure:
DocumentSet:
id: int
documents: list of Document
Document is another Model object with the following structure:
Document:
id: int
...other fields...
I want to write a #marshal_with decorator that returns the DocumentSet id along with a list of the Document ids like so:
{
id: 5,
document_ids: [1, 2, 3]
}
I've been banging my head against the output marshaling syntax to no avail. Some of the things I've tried:
{'id': fields.Integer, 'document_ids':fields.List(fields.Integer, attribute='documents.id')}
{'id': fields.Integer, 'document_ids':fields.List(fields.Nested({'id':fields.Integer}), attribute='documents')}
What's the magic incantation?

The magic incantation is
{'id': fields.Integer, 'name': fields.String, 'document-ids':{'id': fields.Integer}}
It was right there in the "Complex Structures" paragraph in the documentation.

Related

Using hasMany relation and cascading ORM level in loopback4

I have created 2 models Author and Books where Author has hasMany relation with Book and Book has belongsTo relation with author.
While saving data using ORM models the cascading is not happening i.e
{
"authorId": 1,
"name": "qwery",
"experience": 2,
"books": [{
"BookId": 12,
"category": "string"
}]
}
The above should create a Author record in Author table and create a Book record with the authorId in Book table, which is not happening whereas from belongsTo it can able to create an Author record with just authorId.
You can find the code in the following GIT
You need to create a AuthorBookController to connect the two. Please see example code in here: https://github.com/strongloop/loopback-next/blob/master/examples/todo-list/src/controllers/todo-list-todo.controller.ts

Create multiple (two) source with chartit in Django

I'm using chartit in a django project.
I have a models (ReadingSensor) with the following attributes:
id_sensor
date_time
value
I want to create a line chart with several lines for different id_sensors
for example:
ReadingSensor.objects.filter(id_sensor=2)
ReadingSensor.objects.filter(id_sensor=1)
For a single model we have:
ds = DataPool(
series=
[{'options': {
'source': MonthlyWeatherByCity.objects.all()},
'terms': [
'month',
'houston_temp',
'boston_temp']}
])
cht = Chart(
datasource = ds,
series_options =
[{'options':{
'type': 'line',
'stacking': False},
'terms':{
'month': [
'boston_temp',
'houston_temp']
}}],
chart_options =
{'title': {
'text': 'Weather Data of Boston and Houston'},
'xAxis': {
'title': {
'text': 'Month number'}}})
Documentation: http://chartit.shutupandship.com/docs/
I consulted the documentation but found no suggestive example to help me.
Can someone help me?
Actually the example is on the site you provide, please check this link: http://chartit.shutupandship.com/demo/chart/multi-table-same-x/
The idea is just to add more items with options and terms to the series list when constructing DataPool object and adjust the terms in series_options when constructing Chart object accordingly.
Then you may find it's helpful to adjust the field name for the case when two data sources have the fields with the same name, the detailed document regarding to this issue is here: http://chartit.shutupandship.com/docs/apireference.html#datapool

Using knockout destroy() with django deserializer

In knockout.js there is a function called destroy() See bottom of this page
It says that it is useful for Rails developers as it adds a _destroy attribute to a object in an observerable array
Im using django and trying to use the same function to know which objects to delete from my database - and as far as i understand a django deserialized object only contains the and pk what is in the fields object
this is what the json looks like:
{"pk": 1,
"model": "eventmanager.datetimelocgroup",
"fields": {"event": 10},
"_destroy": "true"
}
As of now i have very ugly but working code - i was wondering if there is any shorter way to detect if a deserialized object had a destroy flag
my current code looks like this
ra = []
removejson = json.loads(eventslist)
for i,a in enumerate(removejson):
if '_destroy' in a:
ra.append(i)
for index,event in enumerate(serializers.deserialize("json", eventslist)):
if index in ra:
try:
e = Event.objects.get(id = event.object.pk)
e.delete()
except ObjectDoesNotExist:
pass
else:
event.save()
I was wondering if there is a better way than going through the json multiple time
This oneliner should work (please understand it before trying it out):
Event.objects.filter(
id__in = [
x['fields']['event'] for x in json.loads(eventslist) if '_destroy' in x
]
).delete()

How to pass data from django to d3.js

I'm doing a survey web project at the moment that requires me to use d3.js to perform some kind of bar chart visualization. I'm using Django to program my web application.
The problem I encounter is how do I pass all values related to an object into an array that is used in d3.js?
choice = question.choicelist.get(choice_no=choice_no)
where votes for each choices to the question will be choice 1 = 4, choice 2 = 6, choice 3 = 7, choice 4 = 1.
For ds.js, the most simplest way to read a data set is:
var data = [ 4, 6, 7, 1]
How do I pass the data to my template such that d3.js is able to read it as the code above?
Handiest option: convert it to json. Json is valid javascript, so you can insert it directly into the template, which seems to be what you want. Something like
import json
def your_view(request):
poll_results = [4, 6, 7, 1]
poll_as_json = json.dumps(poll_results)
# Gives you a string '[4, 6, 7, 1]'
...
return render_or_whatever(context={'poll_as_json': poll_as_json})
And in your template:
<script ...>
var data = {{ poll_as_json }};
...
</script>
Something like that?

Django: Data corrupted after loading? (possible programmer error)

I may be loading data the wrong way.
excerpt of data.json:
{
"pk": "1",
"model": "myapp.Course",
"fields":
{
"name": "Introduction to Web Design",
"requiredFor": [9],
"offeringSchool": 1,
"pre_reqs": [],
"offeredIn": [1, 5, 9]
}
},
I run python manage.py loaddata -v2 data:
Installed 36 object(s) from 1
fixture(s)
Then, I go to check the above object using the Django shell:
>>> info = Course.objects.filter(id=1)
>>> info.get().pre_reqs.all()
[<Course: Intermediate Web Programming>] # WRONG! There should be no pre-reqs
>>> from django.core import serializers
>>> serializers.serialize("json", info)
'[{"pk": 1, "model": "Apollo.course", "fields": {"pre_reqs": [11], "offeredIn": [1, 5, 9], "offeringSchool": 1, "name": "Introduction to Web Design", "requiredFor": [9]}}]'
The serialized output of the model is not the same as the input that was given to loaddata. The output has a non-empty pre_req list, whereas the input's pre_reqs field is empty. What am I doing wrong?
I think there is already content in your many-to-many table pre_reqs (with FK=1) (before you load your JSON data).
It seems the loader will not delete already existing tuples in many-to-many tables.
Have a look at the django.core.serializer.base.DeserializedObject class.
The DeserializedObject.save method only adds new relations.