开发者

Using get or insert functionality on one to many django models and modelforms

A] Summary:

Using get or insert functionality on one to many django models, checking whether a record or relationship exists prior to adding a new one.

B] Details:

1] I have the following django model structure country (one) to City (many)

2] I am using ModelForm for displaying the form on the html page. The forms are passed as template values and the template values are then rendered on the html page

3] When the post request comes in, the code extracts the country and city form data , checks for validity and saves it.

C] Issue/Item i need help with:

1] I want to use the get_or_insert functionality with my country and city relationship

2] Basically, i want to check whether there is an existing country record in the database for the country selected by the user,

2.1] if the country exists, check if there is a city record for the selected country.

2.1.1] if the city record exists, we are good, no need to add another record

2.1.2] if the city record doesn't exist, create the city record and associate the country with it

2.2] if the country doesn't exist, create the country record, create the city record and associate the city record with the country record.

C] Code Excerpts:

1] Models and forms --

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] code that prints the forms--

user_country_form and user_city_form are passed from python code as template values

 __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 code excerpt which displays the template values on the html page

<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] Code excerpt for saving the data --

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

Thankyou for reading.

[Edit#1]

@ Torsten, post gave me a pointer to get_or_insert, I then came across StackOverflow post (http://stackoverflow.com/questions/4812832/get-or-create-matching-key-and-user-python-app-engine) and implemented the key_name functionality to user get_or_insert

Code for saving the record looks like follows:

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())

Request: Can someone please do a quick code review and let me know if i am doing some开发者_如何学运维thing wrong or making some rookie mistakes?


Use get_or_create (the equivalent to your 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜