func fetch<decodableStruct: Decodable>(url: String, completion: @escaping ([decodableStruct]) -> Void) {
guard let url = URL(string: url) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
DispatchQueue.main.async {
if let error = error {
print(error)
return
}
guard let data = data else { return }
do {
let resultSet = try JSONDecoder().decode([decodableStruct].self, from: data)
completion(resultSet)
} catch {
print(error)
return
}
}
}.resume()
}
fetch(url: "http://localhost:8000/finance/api/tools") { (decodableStruct: [Tool]) in
self.tools = decodableStruct
self.tableView.reloadData()
}
func fetchWithResult<decodableStruct: Decodable>(url: String, completion: @escaping (Result<[decodableStruct], Error>) -> Void) {
guard let url = URL(string: url) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
DispatchQueue.main.async {
if let error = error {
completion(.failure(error))
}
guard let data = data else { return }
do {
let resultSet = try JSONDecoder().decode([decodableStruct].self, from: data)
completion(.success(resultSet))
} catch {
completion(.failure(error))
}
}
}.resume()
}
fetchWithResult(url: "http://localhost:8000/finance/api/tools") { (decodableStruct: [Tool]) in
switch(decodableStruct) {
}
}
struct Supplier: Decodable {
var id: Int
var name: String
var short_name: String
}
struct Tool: Decodable {
var id: Int
var name: String
var code_number: String
}
content_object = GenericForeignKey('content_type', 'object_id')
когда пробовал.
Так получается то, что надо. Осталось что-то придумать с blank=True и сохранить поле модели. Тут наверное прийдется стринг все таки хранить и получать через getattr()