Domanda

I am trying to understand methods in Python.I have two classes in my program.

class Department(ndb.Model):
  dept_name=ndb.StringProperty(required=True)
  employees=ndb.KeyProperty(repeated=True)

and

class Employee(ndb.Model):
   employee_name=ndb.StringProperty(required=True)
   salary=ndb.IntegerProperty()

I have this method in the Department class

def addEmployee(employee):
    dept = Department.get_or_insert("Finance")
    dept.employees.append.(employee.key)
    dept.put()

which i am calling from a RequestHandler like this:

    employee = Employee.get_by_id("David Moyes")
    dept = Department.get_or_insert("Finance")
    dept.addEmployee(employee)

I am trying to add David Moyes to the Finance department.Using his name which is also the key to the David Moyes entity in the Employee datastore.Problem is,nothing happens and no error message is shown. I am suspecting the problem is from the line

def addEmployee(employee):

When i declare this,what Type is employee? shouldn't i be passing in a String instead? Since the key is a String?

È stato utile?

Soluzione

The first argument to instance methods is a handle to the current object, and should be called self. This is standard python oo programming.

Also, loading dept inside the addEmployee method makes no sense - it is hard coded to load "Finance" - what if you wanted to add an employee to the Sales dept?

I think your Department class should look something more like this:

class Department(ndb.Model):
  dept_name = ndb.StringProperty(required=True)
  employees = ndb.KeyProperty(kind=Employee, repeated=True)

  def addEmployee(self, employee):
    self.employees.append(employee.key)
    self.put()

Note I have also added kind=Employee to the employees KeyProperty, which will validate that you only add Keys of type Employee to the list.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top