python - 在一对多 Django 模型和模型形式上使用获取或插入功能

标签 python google-app-engine django-models django-forms

A] 总结:

在一对多 Django 模型上使用获取或插入功能,在添加新记录或关系之前检查记录或关系是否存在。

B] 详细信息:

1] 我有以下 django 模型结构国家(一个)到城市(多个)

2] 我正在使用 ModelForm 在 html 页面上显示表单。表单作为模板值传递,然后模板值呈现在 html 页面上

3] 当 post 请求进来时,代码提取国家和城市表单数据,检查有效性并保存。

C] 我需要帮助的问题/项目:

1] 我想在我的国家和城市关系中使用 get_or_insert 功能

2] 基本上,我想检查数据库中是否存在用户选择的国家/地区的现有国家/地区记录,

2.1]如果国家存在,检查是否有所选国家的城市记录。

2.1.1]如果城市记录存在,我们就可以了,不需要再添加记录

2.1.2]如果城市记录不存在,则创建城市记录并关联国家

2.2] 如果国家不存在,则创建国家记录,创建城市记录,并将城市记录与国家记录相关联。

C] 代码摘录:

1] 模型和表单 --

class UserReportedCountry(db.Model):
country_name = db.StringProperty( required=True,
                          choices=['Afghanistan','Aring land Islands']
                         )

class UserReportedCity(db.Model):
    country = db.ReferenceProperty(UserReportedCountry, collection_name='cities')
    city_name = db.StringProperty(required=True)   

class UserCountryForm(djangoforms.ModelForm):
    class Meta:  
        model = UserReportedCountry

class UserCityForm(djangoforms.ModelForm):
    class Meta:  
        model = UserReportedCity
        exclude = ('country', ) 

2] 打印表单的代码--

user_country_form 和 user_city_form 作为模板值从 python 代码传递

 __TEMPLATE_USER_COUNTRY_FORM = 'user_country_form'
 __TEMPLATE_USER_CITY_FORM = 'user_city_form'

 def get(self): 
   template_values = {
        self.__TEMPLATE_USER_COUNTRY_FORM: UserCountryForm(),
        self.__TEMPLATE_USER_CITY_FORM: UserCityForm()
    }

   #rendering the html page and passing the template_values
   self.response.out.write(template.render(self.__MAIN_HTML_PAGE, template_values))

3] 在 html 页面上显示模板值的 HTML 代码摘录

<div id="userDataForm">
<form method="POST" action="/UserReporting"> 
<table>
<!-- Printing the forms for users country, city -->
    {{ user_country_form }}
    {{ user_city_form }}     
 </table>
 <input type="submit" name="submit" value= "submit">
 </form>
 </div>

3] 保存数据的代码摘录 --

def post(self):
    self.store_user_data()
    self.redirect('/')

#method to save users data in the models UserReportedCountry, UserReportedCity
def store_user_data(self):
    #getting user's country and city
    user_reported_country =  UserCountryForm(self.request.POST)
    user_reported_city = UserCityForm(self.request.POST)

    if (user_reported_country.is_valid() and user_reported_city.is_valid()):
        #save the country data
        country_entity = user_reported_country.save()
        #save the city data, and relate county with city
        city_entity = user_reported_city.save(commit=False)
        city_entity.country = country_entity 
        city_entity.put()
        return
    else:
        return

感谢阅读。

[编辑#1]

@ Torsten,帖子给了我一个指向 get_or_insert 的指针,然后我看到了 StackOverflow 帖子 (http://stackoverflow.com/questions/4812832/get-or-create-matching-key-and-user-python-app -engine) 并为用户 get_or_insert 实现了 key_name 功能

保存记录的代码如下:

def store_user_data(self):
    #getting user's country and city
    user_reported_country =  UserCountryForm(self.request.POST)
    user_reported_city = UserCityForm(self.request.POST)

    if (user_reported_country.is_valid() and user_reported_city.is_valid()):
        #save the country and city data
        country_record = self.store_country_data()
        city_record = self.store_city_data(country_record)
        return
    else:
        return

def store_country_data(self):
    user_reported_country_name = self.request.POST['country_name']
    key_name = self.sanitize_key_name(user_reported_country_name)
    country_entity = UserReportedCountry.get_or_insert(key_name, country_name = user_reported_country_name)
    country_entity.put()
    return country_entity

def store_city_data(self, country_record):
    user_reported_city_name = self.request.POST['city_name']
    key_name = self.sanitize_key_name("%s:%s" % (country_record.country_name, str(user_reported_city_name)) )
    city_entity = UserReportedCity.get_or_insert(key_name, 
                                                 city_name = user_reported_city_name, 
                                                 country= country_record)

    city_entity.put()
    return city_entity

def sanitize_key_name(self,key_name):
    return re.sub(r'\s', '', key_name.lower())

请求:有人可以快速审查代码,如果我做错了什么或犯了一些新手错误,请告诉我吗?

最佳答案

使用 get_or_create(等同于您的 get_or_insert):

country, country_is_new = UserReportedCountry.objects.get_or_create(country_name=my_country_name)
city, city_is_new = UserReportedCity.objects.get_or_create(country=country, city_name=my_city_name)

关于python - 在一对多 Django 模型和模型形式上使用获取或插入功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5560749/

相关文章:

python - 如何从 AWS Lambda 函数建立 Oracle 数据库连接 (Python)

google-app-engine - app-engine-patch 和 pyFacebook 不工作

ios - 使用 XMPP 作为推送服务器?

django 迁移 hell ,掉了一张 table 。试图取回它

python - get_or_create() 问题

python - 如何在 Pandas 数据框中找到每一行的顶部列值

python - Pyro4 和普通的旧数据对象

google-app-engine - 在谷歌应用引擎中部署应用

django - 根据相关对象的存在过滤 Django 模型

python - 使用 Python 从电子邮件中提取文本