How t do recursive model in sqlalchamy? - sqlalchemy

I want to do recursive model like this, but is this the right way t do it? also, I am using ariadne graphql, so i should make specific schema.graphql not sure how to do that yet.
class File(Base):
__tablename__ = "files"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
content = Column(String)
time_created = Column(DateTime(timezone=True), server_default=func.now())
parent_id = Column(Integer, relation_to="files.id")
parent = relationship("File", back_populates="children")
children = relationship("File", back_populates="parent")
my schema
extend type Mutation {
file(name: String!, content: String, parent_id:Int): String!
}
type File {
name: String
children: [File]
}
extend type Query {
files : [File]
}
goal:
I want to receive something like this
[
{
"name":"untitled",
"id":234,
"children":[
{
"name":"my file",
"id":235
},
{
"name":"my other file",
"id":236,
"children":[
{
"name":"my file",
"id":237
},
]
}
]
},
{
"name":"my notes",
"id":225
}
]

Related

How to get data from mysql reverse foreign key without using the prefetch concept?

I have two models, Like,
class User(models.Model):
fname = models.CharField(max_length=32, blank=True, null=True)
class Meta:
managed = True
db_table = 'u_users'
class Email(models.Model):
usr_id = models.ForeignKey(User, db_column='usr_id', related_name='emails', on_delete=models.CASCADE)
email = models.EmailField(max_length=64)
class Meta:
managed = True
db_table = 'u_email'
Now i'would like to get list of users with list of email each users have
Sample output.
[
{
"id":1,
"fname":"Test User",
"emails":[
{
"id":1,
"email":"masstmp+2ffj7#gmail.com"
},
{
"id":2,
"email":"masstmp+2ffj8#gmail.com"
}
]
},
{
"id":2,
"fname":"Test User2",
"emails":[
{
"id":3,
"email":"masstmp+2ffj9#gmail.com"
},
{
"id":4,
"email":"masstmp+2ffj10#gmail.com"
}
]
}
]
But i need to get this output using single query. In raw query i able to write the query and get the output easy. But i want to know about how to do this in ORM.
Please, Thank you.

SwiftUI List from JSON/Dictionary

Just starting out with SwiftUI so apologies for the basic question. I have a dictionary created from a JSON file of the following format:
{
{
"first_name": "John",
"last_name": "Doe",
"email": "John.doe#domain.com"
},
{
"first_name": "Jane",
"last_name": "Doe",
"email": "Jane.doe#domain.com"
}
}
I would like to create a list of first_name that I can then use in other files, the names are unique so there shouldn't be any need for UUID. So far I can load my data into a swift file and display it with the use of:
struct DataTest: View {
let people = Bundle.main.decode("people.json")
var body: some View {
VStack{
ForEach(0 ..< people.count){number in
Text("\(people[number].first_name)")
}
}
}
}
Is there any way that I can generate an array or list without the use of a ForEach loop? I tied something like #State private var = people.first_name, but that did not seem to work.
Assuming that the is this structure:
struct Person {
var first_name : String
var last_name : String
var email: String
}
and people is [Person], you can map a single property like this:
let firstNamesOnly = people.map { $0.first_name }
or, newly in Swift 5.2:
let firstNamesOnly = people.map(\.first_name)
You could use this in a computed property and List by doing:
var firstNames : [String] {
people.map(\.first_name)
}
var body: some View {
VStack{
ForEach(firstNames, id: \.self) { firstName in
Text(firstName)
}
}
}

Unable to create converter for class when using sealed class or an interface with Moshi

I am trying to parse a json data from a server.It has dynamic keys so I am trying to have like a parent class that have the shared keys and child class for each specific node. I wrote a kotlin code using retrofit and Moshi but it's not working. I tried with a sealed class and interface without success. Actually I would prefer that works with sealed class but I don't know what I am doing wrong
interface MyApi {
#GET("/...")
fun fetchMyFeed(): Call<MyResponse>
}
data class MyResponse(
val data: List<ParentResponse>
)
interface ParentResponse{
val name: String
}
data class Child1Response(
val age: String,
val kids: List<KidsResponse>,
val cars: List<CarsResponse>
)
data class Child2Response(
val job: String,
val address: List<AddressResponse>
)
fun fetchAllFeed(): List<Any>? =
try {
val response = api.fetchMyFeed().execute()
if (response.isSuccessful) {
Log.d("check",${response.body()?.data?})
null
} else null
} catch (e: IOException) {
null
} catch (e: RuntimeException) {
null
}```
and the json file is :
{
"data": [
{
"name": "string",
"job": "string",
"address": [
{
"avenue": "string",
"imageUrl": "string",
"description": "string"
}
]
},
{
"name": "string",
"age": "string",
"kids": {
"count": "string",
"working": "string"
},
"cars": [
{
"brand": "string",
"age": "string",
"imageUrl": "string"
}
]
}
]
}
Unable to create converter for class
You can make use of JsonAdapter from moshi to parse different JSON Models if you can differentiate them by foreseeing some value in the json.
for example, consider json response having two schemas,
{
"root": {
"subroot": {
"prop" : "hello",
"type" : "String"
}
}
}
(or)
{
"root": {
"subroot": {
"prop" : 100,
"type" : "Integer"
}
}
}
Here, subroot has different schemas (one containing string property and another containg a integer property) which can be identified by "type"
You can create a parent sealed class with common keys and derive few child classes with varying keys. Write a adapter to select the type of class to be used while json serialization and add that adapter to moshi builder.
Model classes:
class Response {
#Json(name = "root")
val root: Root? = null
}
class Root {
#Json(name = "subroot")
val subroot: HybridModel? = null
}
sealed class HybridModel {
#Json(name = "type")
val type: String? = null
class StringModel : HybridModel() {
#Json(name = "prop")
val prop: String? = null
}
class IntegerModel : HybridModel() {
#Json(name = "prop")
val prop: Int? = null
}
}
Few extension methods to JsonReader,
inline fun JsonReader.readObject(process: () -> Unit) {
beginObject()
while (hasNext()) {
process()
}
endObject()
}
fun JsonReader.skipNameAndValue() {
skipName()
skipValue()
}
HybridAdapter to select type of class for "subroot" key
class HybridAdapter : JsonAdapter<HybridModel>() {
#FromJson
override fun fromJson(reader: JsonReader): HybridModel {
var type: String = ""
// copy reader and foresee type
val copy = reader.peekJson()
copy.readObject {
when (copy.selectName(JsonReader.Options.of("type"))) {
0 -> {
type = copy.nextString()
}
else -> copy.skipNameAndValue()
}
}
//handle exception if type cannot be identified
if (type.isEmpty()) throw JsonDataException("missing type")
// build model based on type
val moshi = Moshi.Builder().build()
return if (type == "String")
moshi.adapter(HybridModel.StringModel::class.java).fromJson(reader)!!
else
moshi.adapter(HybridModel.IntegerModel::class.java).fromJson(reader)!!
}
#ToJson
override fun toJson(p0: JsonWriter, p1: HybridModel?) {
// serialization logic
}
}
Finally build Moshi with the HybridAdapter to serialize HybridModel,
fun printProp(response: Response?) {
val subroot = response?.root?.subroot
when (subroot) {
is HybridModel.StringModel -> println("string model: ${subroot.prop}")
is HybridModel.IntegerModel -> println("Integer model: ${subroot.prop}")
}
}
fun main() {
val jsonWithStringSubroot =
"""
{
"root": {
"subroot": {
"prop" : "hello",
"type" : "String"
}
}
}
"""
val jsonWithIntegerSubroot =
"""
{
"root": {
"subroot": {
"prop" : 1,
"type" : "Integer"
}
}
}
"""
val moshi = Moshi.Builder().add(HybridAdapter()).build()
val response1 = moshi.adapter(Response::class.java).fromJson(jsonWithStringSubroot)
printProp(response1) // contains HybridModel.StringModel
val response2 = moshi.adapter(Response::class.java).fromJson(jsonWithIntegerSubroot)
printProp(response2) // contains HybridModel.IntegerModel
}

How to parse Json array object?

I am trying to parse a Json file in Qt application but i am stuck at a point.
I have a json file which contains arrays with properties. Now i have a Category class which has a items as member variable. Now i would like to parse the properties and create a unique category object and under this object i would like to add the properties.
I have achieved this by hardcoding:
auto vehicle = std::make_unique<Item>("Coordinates");
vehicle->addEntry(std::make_unique<PropertyItem>("TODO", "x", PropertyType::FLOAT, false, *vehicle.get()));
categories.emplace_back(std::move(vehicle));
void Model::loadItemsFromJson() {
// Vehicle
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json");
QJsonArray properties = obj["properties"].toArray();
/// No idea here how to achive
}
Should i change the Json for better handling or could this be achieved easily?
Thank you
--------------------------EDIT---------------------
Now my json looks like this:
{
"General": [{
"Address": "TODO",
"Readonly": false
},
],
"Coordinates": [{
"Address": "TODO",
"Readonly": false
}
]
]
}
and my implementation:
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json");
QVariantMap map = obj.toVariantMap();
for (auto& m : map.keys()) {
// How to create objects??
}
If you structure your JSON like your objects, e.g.
{
"Categories" : {
"General" : [{
"Address" : "TODO",
"Name" : "Name",
"Type" : "string",
"ReadOnly" : "true"
}, ...],
"World Coordinates" : [...]
}
Then you just parse out each CategoryItem and ScenarioPropertyItem
PropertyType toPropertyType(QJsonValue value); // forward declare
void ScenarioPropertiesModel::loadItemsFromJson() {
// Vehicle
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json")["Categories"].toObject();
for (auto & cat : obj)
{
auto category = std::make_unique<CategoryItem>(cat.name());
for (auto & prop : cat.value().toArray())
{
auto address = prop["Address"].toString();
auto name = prop["Name"].toString();
auto type = toPropertyType(prop["Type"]);
auto readonly = prop["Readonly"].toBool();
category->addEntry(std::make_unique<ScenarioPropertyItem>(address, name, type, readonly));
}
categories.emplace_back(std::move(category));
}
}
PropertyType toPropertyType(QJsonValue value)
{
static std::map<QString, PropertyType> propertyTypes =
{
{ "float", PropertyType::FLOAT },
{ "string", PropertyType::String },
// etc
}
return propertyTypes[value.toString()];
}

Get JSON element swift

I am working receiving the following JSON file in Swift and I cant figure out how get the details elements in the JSON
[
{
"id": 143369,
"history": "jd2",
"details": [
{
"name": "Su 1",
"color": "#ffffff"
},
{
"name": "Stu 1",
"color": "#ffffff"
}
]
},
{
"id": 143369,
"history": "musa 2",
"details": [
{
"name": "Stu 1",
"color": "#ffffff"
},
{
"name": "Stu 2",
"color": "#ffffff"
}
]
}
]
I have created this class with which I am able to retrieve id and history but not the details. How do I include the details with the id and history?
public class students {
let id: Int32
let history: String?
init(id:Int32, history:String) {
self.id = id
self.history = name
}
}
Below is my web service code.
var dataArray = [students]()
Alamofire.request(.GET, url)
.responseJSON { response in
if let value: AnyObject = response.result.value {
let json = JSON(value)
if let items = json.array {
for item in items {
self.dataArray.append(students(
id: item["id"].int32!,
history: item["history"].string!))
let cItems = item["details"].array
for citem in citems {
//here
}
}
}
}
}
your student model should be like this.
let id: Int32
let history: String?
let details: Array<[String:AnyObject]>
init(id:Int32, history:String,details:Array<[String:AnyObject]>) {
self.id = id
self.history = name
self.details= details //need a cast here!
}
here is a simple parser for i used for a project to cast your Array<[String:AnyObject]> as you
func collection(data:[[String:AnyObject]]) -> [yourModel] {
var objectArray: [yourModel] = []
for d in data {
let obj = yourModel(data: d as [String: AnyObject]) // i created a initializer for this object here on my project.
objectArray.append(obj)
}
return objectArray
}
hope gives an idea!