what is the efficient way to update existing child and append new child object to parent in SQLAlchemy? - sqlalchemy

What is the efficient way to update existing child model and add new child model to parent model also remove child model?
I just
child_inputs = [{'child_id':1, 'name': 'test1'},{'name': 'test2'}]
parent = Parent.query.get(id)
// remove child model if not exists in child_inputs like child_id 2 appended to Parent model
for inputs in child_inputs:
if 'child_id' in inputs:
child = Child.query.get(inputs['child_id'])
child.name = inputs['name']
else:
child = Child(**inputs)
parent.append(child)
db.session.commit()

I think the documentation of the Merging usage is exactly what you need.
You need to make sure that the 'child_id' is actually the name of the primary key field, or just rename the key before processing through the merge.

Related

how to iterate over a nested json array and update the properties of node based on a condition?

I want to create new properties for a pre-existing node based on a condition. To be more specific, I want to create a new node property when a node property matches with a property within the nested JSON array.
call apoc.load.json("file:///precedence.json")yield value as line
foreach(link in line.link| match (n) where n.id=link.source)
return n
returns an error
Neo.ClientError.Statement.SyntaxError: Invalid use of MATCH inside FOREACH (line 2, column 28 (offset: 93))
"foreach(link in line.link| match (n) where n.id=link.source)"
I have a nested json array called link inside demo.json- i want to check if my node property matches with the property in link- if it does then i want to create a new property in that particuar node

How to iterate over a nested json array and change the node properties based on a condition?

I want to create new properties for a pre-existing node based on a condition. To be more specific, I want to create a new node property when a node property matches with a property within the nested JSON array. my json structure looks something like this:
{"some tasks":[
{"id":1,"name":"John Doe"},
{"id":2,"name":"Jane Doe"}
],
"some links":[
{"id":1,"type":"cartoon"}
{"id":2,"type":"anime"}
]
}
I already created nodes with properties from tasks - now I want to iterate over the links part and update the properties of the node when the ids match. I tried using foreach like so-
call apoc.load.json("file:///precedence.json")yield value as line
foreach(link in line.link| match (n) where n.id=link.source)
return n
which returns the error-
Neo.ClientError.Statement.SyntaxError: Invalid use of MATCH inside FOREACH (line 2, column 28 (offset: 93))
"foreach(link in line.link| match (n) where n.id=link.source)"
so how do i check this condition inside foreach?
You can't use a MATCH inside a FOREACH, it only allows updating clauses.
Instead you can UNWIND the list back into rows (you'll have a row per entry in the list) then you can MATCH and SET as needed.
I also highly recommend using labels in your query, and ensuring you have in index on the label and id property for fast lookups. For this example I'll use :Node as the label (so for the example you would have :Node(id) for the index):
CALL apoc.load.json("file:///precedence.json") yield value as line
UNWIND line.link as link
MATCH (n:Node)
WHERE n.id = link.source
SET n.type = link.type

Updating Data within a unique randomly generated ID/KEY in firebase using HTML

function updateFirebase(){
const fb=firebase.database().ref()
//get field values
author = document.getElementById('uname').value
user_email = document.getElementById('umail').value
data = {author, user_email}
//update database
fb.child('Article/').update(data);
}
</script>
I have problem with my code. I want to update the data inside a table named "Article". Article has generated items with a unique key/id and each key has its own content. Lets say I want to be able to edit the "author" or change the "title", the problem is they each have a randomly generated key/id that I cant access. for example that "-LS39kReBHrKGqNj7h_". I can only save the data inside the "Article" tree but I cant change the "author" or the "title". How do i get a workaround this so I can change those properties?
Here is how my firebase looks like
It depends whether you have the record reference on the frontend before update or not (whether you have fetched it before you are trying to update it).
But generally, you have two options
You can store the key reference as an "id" field on the object.
To achieve that, you need two step process when creating the record at the first place
// Creates a new record in DB and returns it to you. Now you can get the "key"
const newRecord = firebase.database().ref('TABLE_NAME_REF').push();
newRecord.set({
id: newRecord.key
...
});
This is great if you fetch the list of records on the frontend and then you want to update one of them. Then you can just build the ref path like this
fb.child('Article/' + record.id ).update(data); // where record is the prefetched thing
You need to find the element based on its fields first. And once you have it, you can update it right away.
To achieve this, you can simply do something like:
firebase.database()
.ref('TABLE_NAME_REF') // let's say 'Article'
.orderByChild('RECORD_KEY') // Let's say 'author'
.equalTo('KEY_VALUE') // let's say 'zoranm'
.limitToFirst(1)
.once("value")
.then(res => {
// You need to loop, it always returns an array
res.forEach(record => {
console.log(record.key); // Here you get access to the "key"
fb.child('Article/' + record.key ).update(data); // This is your code pasted here
})
})

How to define recursive transforms for J2H?

I'm evaluating to use J2H (http://json2html.com/examples/) to render JSON structures.
My JSON are complex trees, with many repeated (recursive) structures.
My question is about how to define a transform that can be applied at many levels of the JSON tree when it finds nodes of the same type/structure (I can add type or class attributes to know which nodes are of the same type).
Example:
+ root type=node
+ child type=attribute
+ child type=node
+ child type=attribute
+ child type=attribute
+ child type=node_primitive
+ child type=primitive
+ child type=attribute
+ child type=node
On that tree we have types: node, attribute, node_primitive and primitive that can be on different levels of the tree. And nodes of the same type will have the same structure.
You should be able to do something like this using inline functions and nested transforms (http://json2html.com/examples/#example-basic-nested)
For example if you want to have a specific child based on a type json field you can do something like this
var transforms = {
'attribute':{'<>':'div','text':'Attribute'},
'node':{'<>':'div','text':'Node'},
'list':{'<>':'li','html':function(){
return( json2html.transform(this,transforms[this.type]) );
}},
var data = [
{'type':'node'},
{'type':'attribute'}
];
document.write( json2html.transform(data,transforms.list) );
If your JSON structure has more than one level of depth you could recursively call the following within the inline function of the root node.
json2html.transform(this.child,transforms.list)

Is Not JSON Serializable odoo computed one2many error

this is really good explanation about new API.
Also, I have question regarding computed one2many field. Consider this as example
Class parent has computed one2many field to Class child. I want that the one2many field is automatically filled with some random value.
So, I give my fields compute. Also make a method with #api.depends("some_field").
To insert a value to one2many field from the methods, i use childfield += self.env['class_child'].new({'key':value}).
At parent creation, it works fine, the one2many field is updated everytime the depended field is changed. The problem is at parent edit, when I tried to change the depends value, it got error :
TypeError: is not JSON serializable
I don't understand what wrong with my concept, am I wrong? or do i need to use another method when editing the parent class.
Thx
Try this type of code:
self.env['class_child'].create({
'key': [(0, 0, {'field_name1': 'field Value', 'field_name2': 'field value'})]
For a one2many field, a lits of tuples is expected.
Here is the list of tuple that are accepted, with the corresponding semantics:
(0, 0, { values }) #link to a new record that needs to be created with the given values dictionary
(1, ID, { values }) #update the linked record with id = ID (write values on it)
(2, ID) #remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
Example:
[(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})]