How to create a nested dictionary from a datastore model? - google-app-engine

I am working on this problem a couple of days, my idea is from this model:
class oceni(db.Model):
user = db.UserProperty()
weight = db.FloatProperty()
item = db.StringProperty()
..to create a dictionary in this format:
collection = dict()
collection = {
'user1':{'item1':weight1,'item2':weight2..},
'user2':{'item3':weight3,'item4':weight4..},
..}
..and as far as I reached is this:
kontenier = db.GqlQuery('SELECT * FROM oceni')
kolekcija = dict()
tmp = dict()
lista = []
for it in kontenier:
lista.append(it.user)
set = []
for e in lista:
if e not in set:
set.append(e)
for i in set:
kontenier = db.GqlQuery('SELECT * FROM oceni WHERE user=:1',i)
for it in kontenier:
tmp[it.item]=it.weight
kolekcija[i]=tmp
..but this creates a dictionary where all the users have the same dictionary with items and their weight. I know this isn't the most pythonic way, but I'm new to this so I will be eager to learn something more about this problem.

I've used your variable names your notation in this snippet.
kontenier = db.GqlQuery('SELECT * FROM oceni')
kolekcija = {}
for it in kontenier:
if it.user not in kolekcija:
kolekcija[it.user] = {}
kolekcija[it.user][it.item] = it.weight

Related

Add M2M field using create(): Django

I have a lot of doubts about managing the M2m field, I finally got a solution to add that data to a model, but there are still some issues, give me a solution to overcome this,
class CourseListSerializer(serializers.ModelSerializer):
instructors = serializers.SerializerMethodField()
image = FileField()
keyarea = CourseKeyAreaSerializer
subject = CourseSubjectsSerializer
sections = serializers.ListField(write_only=True)
beneficiaries = serializers.ListField(write_only=True)
section = CourseSectionSerializers
beneficiary = CourseBeneficiarySerializer
def create(self, validated_data):
data = validated_data
try:
new = Course.objects.create(image=data['image'], name=data['name'], description=data['description'], is_free=data['is_free'],
keyarea=data['keyarea'], subject=data['subject'])
new.save()
beneficiary_data = data['beneficiaries']
new.beneficiary.set(*[beneficiary_data])
section_data = data['sections']
new.section.set(*[section_data])
return new
except Exception as e:
e = "invalid data"
return e
here first creating the "new" object after that to set the M2M field like
"new.beneficiary.set(*[beneficiary_data])"
but is there any way to add beneficiary and section like this
"new = Course.objects.create(image=data['image'],name=data['name'], description=data['description'],is_free=data['is_free'],....)"

Shoveling objects into an array

I'm working on scraping.
class MMA::School
attr_accessor :name, :location_info, :url
def self.today
self.schools
end
def self.schools
schools = []
schools << self.scrape_cbs
schools
end
def self.scrape_cbs
doc = Nokogiri::HTML(open("http://newyork.cbslocal.com/top-lists/5-best-mma-and-martial-arts-studios-in-new-york/"))
schools_1 = self.new
schools_1.name = doc.search("//div/p/strong/span").text.strip
schools_1.location_info = doc.search("//div/p")[4].text.strip
schools_1.url = doc.search("//div/p/a")[0].text.strip
schools_1
schools_2 = self.new
schools_2.name = doc.search("//div/p/span")[0].text.strip
schools_2.location_info = doc.search("//div/p")[7].text.strip
schools_2.url = doc.search("//div/p/a")[2].text.strip
schools_2
schools_3 = self.new
schools_3.name = doc.search("//div/p/span")[1].text.strip
schools_3.location_info = doc.search("//div/p")[9].text.strip
schools_3.url = doc.search("//div/p/a")[3].text.strip
schools_3
schools_4 = self.new
schools_4.name = doc.search("//div/p/span")[2].text.strip
schools_4.location_info = doc.search("//div/p")[12].text.strip
schools_4.url = doc.search("//div/p/a")[5].text.strip
schools_4
schools_5 = self.new
schools_5.name = doc.search("//div/p/span")[3].text.strip
schools_5.location_info = doc.search("//div/p")[14].text.strip
schools_5.url = doc.search("//div/p/a")[6].text.strip
schools_5
end
end
I have some trouble placing my scraped data into an empty array. It only pushes one of the schools_1 etc. to the schools array.
Does anyone have any suggestions on how to fix this?
Without any explanation, it is absolutely not clear what you are trying to do, but it is clear that in your self.scrape_cbs definition, the lines:
schools_1
...
schools_2
...
...
schools_4
are meaningless. Perhaps, you intended to return an array like this from this method:
[schools_1, schools_2, ..., schools_5]
If so, put the line above as the last line of your method definition of self.scrape_cbs.

Returning a dictionary from a file

I have have written this code defining a class
class OrderRecord:
"""Defines an OrderRecord class, suitable for use in keeping track of order records"""
import tools2
def __init__(self, string):
"""Creates a new OrderRecord object"""
string = string.split(',')
self.date = string[0]
self.location = string[1]
self.name = string[2]
self.colour = string[3]
self.order_num = string[4]
self.cost = 0
def cost_of_order(self):
"""Creates a list of the name and adds up the cost of each letter"""
letter = list(self.name)
for let in letter:
self.cost = self.cost + self.tools2.letter_price(let, self.colour)
return self.cost
def __str__(self):
"""Calls the cost_of_order function and returns the split string in the required format"""
self.cost = self.cost_of_order()
return("Date: {0}\nLocation: {1}\nName: {2}\nColour: \
{3}\nOrder Num: {4}\nCost: {5:.2f}".format(self.date, self.location, \
self.name, self.colour, self.order_num, self.cost))
Now I need to write a function that reads a file containing the following:
20130902,Te Rakipaewhenua,Vinas,parauri,8638
20130909,Te Papaioea,McClary,kikorangi,11643
20131215,Kapiti,Labrie,kikorangi,65291
20141106,Waihopai,Labrie,ma,57910
and returns a dictionary that has the location as the key and lists of OrderRecords as the values.
I know this isn't too hard of a task but I have been stuck on this for awhile because I can't get my head around what to do for it.
Any help would be appreciated.
Maybe something like this. It is not the solution but it has what you need with some modifications.
import collections
dct_result = collections.defaultdict(list)
for line in open('file_path'):
fields = line.split(',')
# index 1 being the second column
dct_result[field(1)].append(OrderRecord( some args ))

Acessing content of Instance variable in Post method

Below is a fragement of my code
def LoadCategory(self, filter_string):
time.sleep(1)
self.heading = ""
self.Question_title = list()
self.Question_tag = list()
self.Question_body = list()
self.Question_who_ask = list()
self.Question_who_email = list()
self.Question_key = list()
self.Question_Date = list()
# list is then populated
def post(self):
self.response.write(self.Question_body)
# want to print out self.Question_body in post method.
But the list is empty. what is the right way to access the content of the variable ?
Quick solution assuming you are inside a request class. Although using self to assign variables to the class is not a good approach as said before.
def LoadCategory(self, filter_string):
time.sleep(1)
self.heading = ""
self.Question_title = list()
self.Question_tag = list()
self.Question_body = list()
self.Question_who_ask = list()
self.Question_who_email = list()
self.Question_key = list()
self.Question_Date = list()
# list is then populated
def post(self):
self.LoadCategory(filter_string)
self.response.write(self.Question_body)
Also it would be better if you name LoadCategory to load_category or loadcategory. Try following the PEP8 which states that the function names should be lowercase

Google App Engine - Datastore - GQL Query

class ProjectCategory(db.Model):
name = db.StringProperty("Category name", required = True)
def __str__(self):
return str(self.name)
class Project(db.Model):
name = db.StringProperty("Name", required = True)
category = db.ReferenceProperty(ProjectCategory)
description = db.TextProperty("Description", required = True)
#file_name = db.StringProperty("File name", required = True)
file = db.BlobProperty("Image")
whenstarted = db.DateTimeProperty("Start time")
whenended = db.DateTimeProperty("End Time")
def __str__(self):
return str(self.title)
How to get all Projects where category is CatName
hmm
db.GqlQuery("SELECT * FROM Project WHERE category = :1", "CatName")
don't work ?
The query does not work because you are passing a "CatName" string instead of a ProjectCategory instance's key.
Retrieve your desired ProjectCategory entity from Datastore first with:
pjc = GqlQuery("SELECT * FROM ProjectCategory WHERE name = :1", "CatName").get()
then use it as parameter in the query like this:
db.GqlQuery("SELECT * FROM Project WHERE category = :1", pjc.key())
A second approach is to use the implicit modelname_set Property of the ProjectCategory instance:
pjc = GqlQuery("SELECT * FROM ProjectCategory WHERE name = :1", "CatName").get()
pjc.project_set.fetch(10) #should contains some CatName projects

Resources