سؤال

I recently switched from ext.db to NDB on Google App Engine and am having difficulties (and I am fairly new to OOP).

Problem: User can enter their favorite fruit, score, and comment, which will be saved in a structured list. The user profile page will list the fruit names and a "remove fruit" buttons next to them, and when this is clicked, I want the entry to be removed from the list, hence from the structured list. I was able to remove a element in a list using ext.db without and issue.

This is what I used to have with ext.db, no "score" or "comment" stored:

class UserProfile(db.Model):
        uid            = db.StringProperty(required=True)
        password       = db.StringProperty(required=True)
        firstName      = db.StringProperty(required=True)
        favFruits      = db.StringListProperty()

 def deleteFruit(self, fruitName):
    if fruitName in self.favFruits: # <--favFruit is the list of fruit for a user
        self.favFruits.remove(fruitName)
        self.put()
        return OK
    else:
        return NOT_FOUND

This would remove the name specified by the user fruitName from the database.

I want to do the above, practically speaking, now with a structured list called favFruits using NDB:

 class FavFruits(ndb.Model):
    fruit    = ndb.StringProperty()
    score    = ndb.IntegerProperty()
    comment  = ndb.TextProperty()

 class UserProfile(ndb.Model):
    uid            = ndb.StringProperty(required=True)
    password       = ndb.StringProperty(required=True)
    firstName      = ndb.StringProperty(required=True)
    favFruits      = ndb.StructuredProperty(FavFruits, repeated=True)

I want to find entry in favFruits using user-entered fruitName and delete all elements associated with favFruits for that fruitName (so fruit, score, comment associated with fruit==fruitName be deleted). I would like to avoid looping.

I have tried variations of remove() and delete() combinations without luck. Any guidance will be greatly appreciated!

هل كانت مفيدة؟

المحلول

StructuredProperty is a list but you are now storing a complex object not a basic string, which won't match a Fruit name. Use pop which takes an index as an argument. You will need to find the index of the Fruit you wish to remove, by iterating over the list checking for the Fruit name.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top