[英]Inserting Data in Datastore - App Engine - One to Many
I am a beginner in GAE and python. 我是GAE和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. 您正在尝试将字符串设置为ReferenceProperty,因为self.request.get返回的字符串类型。 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. Product
的' ref_category
'字段是db.ReferenceProperty
,它使用db.Key
或Category
对象,但是您尝试将其设置为字符串。
You can do like this : 您可以这样:
def post(self):
product = Product()
product.ref_category = db.get(self.request.get('ref_category'))
product.put()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.