在一对多django模型和模型上使用get或insert功能

bha*_*esh 5 python google-app-engine django-models django-forms

总结:

在一个到多个django模型上使用get或insert功能,在添加新记录或关系之前检查记录或关系是否存在.

B]详情:

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

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

3]当邮寄请求进入时,代码提取国家和城市表格数据,检查有效性并保存.

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', ) 
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

谢谢你的阅读.

[编辑#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())
Run Code Online (Sandbox Code Playgroud)

请求:有人可以快速进行代码审查,如果我做错了或犯了一些菜鸟错误,请告诉我吗?