I am a beginner in GAE and python. I am having trouble understanding how to insert data with One-to-Many relationship and I don't know much about what I am doing.
I am trying to create an inventory app. Basically, I wanted to insert products under the one category each.
My db Models are below.
class Category(db.Model):
category = db.StringProperty()
date = db.DateTimeProperty(auto_now_add=True)
class Product(db.Model):
ref_category = db.ReferenceProperty(Category)
name = db.StringProperty()
I was able to insert category in the Datastore but products per category is where I am having problem with.
I have a form like below which is I am not sure if this is the correct way too. Is inserting using the key in hidden input fine as well?
<form action="/addproduct" method="post">
<div><label>Product Name:</label><br /><input type="name" name="name" /></div>
<div><input type="hidden" name="ref_category" value="{{selected_category.key()}}" /></div>
<input type="submit" value="Add Candidate">
</form>
Then, my code for insert is below which is I am having trouble. I am trying to understand the resources provided online but my brain cells cannot process it anymore.
def post(self):
product = Product()
product.name = self.request.get('name')
product.ref_category = self.request.get('ref_category')
product.put()
I hope someone help me to understand when solution provided.
You're attempting to set a string to a ReferenceProperty because self.request.get return type of string. The 'ref_category
' field of Product
is a db.ReferenceProperty
, which takes a db.Key
or a Category
object, but you're attempting to set it to a string.
You can do like this :
def post(self):
product = Product()
product.ref_category = db.get(self.request.get('ref_category'))
product.put()