I want to reconstruct django view - python

view.py
class ListDoctor(generics.ListCreateAPIView):
queryset = DoctorList.objects.filter(h_code="h_0001")
serializer_class = DoctorListSerializer
def list(self, request):
doctor = DoctorList.objects.values()
return Response(
{
"doctor": doctor
}
)
data:
"doctor": [
{
"doctorname": "testname1",
"position": "ST",
"h_code_id": "h_0000",
"d_code": "d_0000"
},
{
"doctorname": "testname2",
"position": "CB",
"h_code_id": "h_0000",
"d_code": "d_0001"
},
{
"doctorname": "testname3",
"position": "CM",
"h_code_id": "h_0001",
"d_code": "d_0002"
},
{
"doctorname": "testname4",
"position": "GK",
"h_code_id": "h_0001",
"d_code": "d_0003"
}
]
I would like to change the above code like below.
"h_0000" [
{
"doctorname" : "testname1",
"position" : "ST",
"h_code_id: "h_0000",
"d_code" : "d_0000"
},
{
"doctorname" : "testname2"
"position" : "CB"
"h_code_id: "h_0000",
"d_code" : "d_0001"
}
"h_0001" [
{
"doctorname" : "testname3",
"position" : "CM",
"h_code_id: "h_0001",
"d_code" : "d_0002"
},
{
"doctorname" : "testname4"
"position" : "GK",
"h_code_id: "h_0001",
"d_code" : "d_0003"
}
How can I change the data above to look like below?
We sincerely appreciate those who respond.
h_code_id(h_0001, h_0002, h_0003...) will increase gradually. Therefore, it cannot be manually created.

I assume you want to transform the data in different format.
def list(self, request):
data = {}
doctors = DoctorList.objects.values()
for doctor in doctors:
try:
data[doctor["h_code_id"]].append(doctor)
except KeyError:
data[doctor["h_code_id"]] = [doctor]
return Response(data)

Related

pymongo - Update a data and access the found value

I am trying to update a value of an array stored in a mongodb collection
any_collection: {
{
"_id": "asdw231231"
"values": [
{
"item" : "a"
},
{
"item" : "b"
}
],
"role": "role_one"
},
...many similar
}
the idea is that I want to access values ​​and edit a value with the following code that I found in the mongodb documentation
conn.any_collection.find_one_and_update(
{
"_id": any_id,
"values.item": "b"
},
{
"$set": {
"values.$.item": "new_value" # here the error, ".$."
}
}
)
This should work, but I can't understand what the error is or what is the correct syntax for pymongo. The error is generated when adding "$";
It works fine with my fastAPI.
#app.get("/find/{id}")
async def root(id: int):
db = get_database()
q = {'_id': 'asdw231231','values.item': 'b'}
u = {'$set': {'values.$.item': 'new_value' }}
c = db['any'].find_one_and_update(q, u)
return {"message": c}
mongoplayground

search/filter with list of string graphene-django

I am looking to search for list of different characters/string using graphene-django with single search query run.
class Query(graphene.ObjectType):
candidateInfo = graphene.List(CandidateType, search=graphene.String(),
first=graphene.Int(),
skip=graphene.Int(), last=graphene.Int(),)
def resolve_candidateInfo(self, info, search=None, first=None, last=None, skip=None,
**kwargs):
qs = Candidate.objects.all()
if search:
filter = (
Q(candidateName__icontains=search)|
Q(candidateEmail__icontains=search)|
Q(candidateSkills__icontains=search)
)
qs = qs.filter(filter)
return qs
Here the candidateName, candidateSkills, candidateEmail are in Candidate class with models.CharField
With a single string/character search i am getting correct output. But it fails with list of sting/characters.
Edited: Adding json sample:
[
{
"model": "api.candidate",
"pk": 1,
"fields": {
"candidateName" : "Jack",
"candidateEmail" : "Jack#gmail.com",
"candidateSkills" : ["machine learning", "Artificial Intelligence"]
}
},
{
"model": "api.candidate",
"pk": 2,
"fields":{
"candidateName" : "John",
"candidateEmail" : "John#gmail.com",
"candidateSkills" : ["python", "machine learning"]
}
},
{
"model": "api.candidate",
"pk": 3,
"fields":{
"candidateName" : "Smith",
"candidateEmail" : "Smith#gmail.com",
"candidateSkills" : ["python"]
}
}
]
If query goes in:
query{
candidateInfo(search: "python")
{
candidateName
candidateEmail
}
}
# output must contain data of John and Smith (from sample json)
Also if query is
query{
candidateInfo(search: ["python","artificial intelligence"])
{
candidateName
candidateEmail
}
}
#output must contain data of Jack, John and smith
Adding models of candidate
from django.db import models
class Candidate(models.Model):
candidateName = models.CharField(max_length=100)
candidateEmail = models.CharField(max_length=100)
candidateSkills = models.CharField(max_length=100)
def __str__(self):
return self.candidateSkills
You can run a for loop as such:
qs = Candidate.objects.all()
if search:
if type(search) == list:
qs_l = []
for search_item in search:
filter = (
Q(candidateName__icontains=search_item)|
Q(candidateEmail__icontains=search_item)|
Q(candidateSkills__icontains=search_item)
)
qs_l.append(qs.filter(filter))
qs = qs_l
else:
filter = (
Q(candidateName__icontains=search)|
Q(candidateEmail__icontains=search)|
Q(candidateSkills__icontains=search)
)
qs = qs.filter(filter)
return qs

i want to convert sample JSON data into nested JSON using specific key-value in python

I have below sample data in JSON format :
project_cost_details is my database result set after querying.
{
"1": {
"amount": 0,
"breakdown": [
{
"amount": 169857,
"id": 4,
"name": "SampleData",
"parent_id": "1"
}
],
"id": 1,
"name": "ABC PR"
}
}
Here is full json : https://jsoneditoronline.org/?id=2ce7ab19af6f420397b07b939674f49c
Expected output :https://jsoneditoronline.org/?id=56a47e6f8e424fe8ac58c5e0732168d7
I have this sample JSON which i created using loops in code. But i am stuck at how to convert this to expected JSON format. I am getting sequential changes, need to convert to tree like or nested JSON format.
Trying in Python :
project_cost = {}
for cost in project_cost_details:
if cost.get('Parent_Cost_Type_ID'):
project_id = str(cost.get('Project_ID'))
parent_cost_type_id = str(cost.get('Parent_Cost_Type_ID'))
if project_id not in project_cost:
project_cost[project_id] = {}
if "breakdown" not in project_cost[project_id]:
project_cost[project_id]["breakdown"] = []
if 'amount' not in project_cost[project_id]:
project_cost[project_id]['amount'] = 0
project_cost[project_id]['name'] = cost.get('Title')
project_cost[project_id]['id'] = cost.get('Project_ID')
if parent_cost_type_id == cost.get('Cost_Type_ID'):
project_cost[project_id]['amount'] += int(cost.get('Amount'))
#if parent_cost_type_id is None:
project_cost[project_id]["breakdown"].append(
{
'amount': int(cost.get('Amount')),
'name': cost.get('Name'),
'parent_id': parent_cost_type_id,
'id' : cost.get('Cost_Type_ID')
}
)
from this i am getting sample JSON. It will be good if get in this code only desired format.
Also tried this solution mention here : https://adiyatmubarak.wordpress.com/2015/10/05/group-list-of-dictionary-data-by-particular-key-in-python/
I got approach to convert sample JSON to expected JSON :
data = [
{ "name" : "ABC", "parent":"DEF", },
{ "name" : "DEF", "parent":"null" },
{ "name" : "new_name", "parent":"ABC" },
{ "name" : "new_name2", "parent":"ABC" },
{ "name" : "Foo", "parent":"DEF"},
{ "name" : "Bar", "parent":"null"},
{ "name" : "Chandani", "parent":"new_name", "relation": "rel", "depth": 3 },
{ "name" : "Chandani333", "parent":"new_name", "relation": "rel", "depth": 3 }
]
result = {x.get("name"):x for x in data}
#print(result)
tree = [];
for a in data:
#print(a)
if a.get("parent") in result:
parent = result[a.get("parent")]
else:
parent = ""
if parent:
if "children" not in parent:
parent["children"] = []
parent["children"].append(a)
else:
tree.append(a)
Reference help : http://jsfiddle.net/9FqKS/ this is a JavaScript solution i converted to Python
It seems that you want to get a list of values from a dictionary.
result = [value for key, value in project_cost_details.items()]

Projection using MongoEngine Raw-Query

Does anyone know, how I can implement the following MongoDB query using a MongoEngine Raq-Query?
db.getCollection('subscribers').find({
'_id': ObjectId("579e60b0c525fd2037e8dd31"),
'history.content.read_process_msg': {
'$exists':true
},
'history.content.read_processed': {
'$exists':true
},
'history.content.read_processed': false
},
{'history.$':1})
I read, that the raw-query doesn't support projections and that one should use .only() instead. But the problem here is, that it returns all the empty documents also…
Any advice?
Edit: Here are my models and a sample document:
class Subscriber(Document):
service = StringField()
history = EmbeddedDocumentListField('SubscriberHistory')
def __str__(self):
return self.service
class SubscriberHistory(EmbeddedDocument):
action = StringField()
content = DictField()
def __str__(self):
return self.action
And the sample:
{
"_id" : ObjectId("579e60b0c525fd2037e8dd31"),
"service" : "foo",
"history" : [
{
"action" : "outbound",
"content" : {
"read_processed" : false,
"message_data" : {
"text" : "w00t?"
},
"read_process_msg" : {
"$ref" : "bots_messages",
"$id" : ObjectId("57a6529dc525fd8066ee25b3")
}
},
"created_at" : ISODate("2016-08-06T21:12:00.986Z")
}
]
}

Show ForeignKeyField directly in Flask-Peewee

I have set up an API using the Flask-Peewee API library:
class ActivityResource(RestResource):
exclude = ('id', 'course')
class CourseResource(RestResource):
exclude = ('id')
class SessionResource(RestResource):
def get_query(self):
identifier = get_identifier()
student = Student.get(Student.identifier == identifier)
from = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
to = datetime(2014, 6, 15)
return self.model.select().where(Session.date.between(from, to)).join(Activity).join(Course).join(StuCouRel).join(Student).where(Student.id == student.id).order_by(Session.date, Session.begin_time, Session.end_time)
paginate_by = None
include_resources = {
'activity': ActivityResource,
'course': CourseResource
}
exclude = ('id')
this will output something like this:
[
{
"duration": 7200,
"activity": {
"name": "MyActivityName"
},
"course": {
"name": "MyCourseName"
},
"end_time": "18:00",
"begin_time": "16:00",
"date": "03-04-2014"
},
...
]
what I would like to get, however, is this:
[
{
"duration": 7200,
"activity": "MyActivityName",
"course": "MyCourseName",
"end_time": "18:00",
"begin_time": "16:00",
"date": "03-04-2014"
},
...
]
I have read the docs and tried reading the source code itself, but I can't really figure out how to make it work. Any help would be appreciated.
I made this work using the prepare_data() hook:
def prepare_data(self, obj, data):
data["activity"] = obj.activity.name
data["course"] = obj.course.name
return data

Categories