How to check duplicate data in my datastore and display the error?

落爺英雄遲暮 提交于 2019-12-04 06:28:50

问题


Am working on GAE,GAE datastore and python.

This is my dbmodel.py,

class Customer(db.Model):
    name = db.StringProperty(required=True)
    phone = db.PhoneNumberProperty(required=True)
    email = db.EmailProperty(required=True)

this is my main.py,

class AddCustomerHandler(BaseHandler):
    def get(self):         
        template = jinja_environment.get_template('template/addcustomer.html')
        self.response.out.write(template.render(template_values))

    def post(self):     
        input_fullname=self.request.get('fullname')
        input_phone=self.request.get('phone')
        input_email=self.request.get('email')

        newcustomer=Customer(name=input_fullname,phone=input_phone,email=input_email)

        self.redirect('/addcustomer')

Data store is working fine. I want to check the my newcustomer data duplicate or not based on fullname. if its already entered the data didn't allow to save and need to display the error message. How can i do that?


回答1:


There's good Unique model available in webapp2:

For example, suppose we have a model User with three properties that must be unique across a given group: username, auth_id and email::

class User(model.Model):
    username = model.StringProperty(required=True)
    auth_id = model.StringProperty(required=True)
    email = model.StringProperty(required=True)

To ensure property uniqueness when creating a new User, we first create Unique records for those properties, and if everything goes well we can save the new User record::

@classmethod
def create_user(cls, username, auth_id, email):
    # Assemble the unique values for a given class and attribute scope.
    uniques = [
        'User.username.%s' % username,
        'User.auth_id.%s' % auth_id,
        'User.email.%s' % email,
    ]

    # Create the unique username, auth_id and email.
    success, existing = Unique.create_multi(uniques)

    if success:
        # The unique values were created, so we can save the user.
        user = User(username=username, auth_id=auth_id, email=email)
        user.put()
        return user
    else:
        # At least one of the values is not unique.
        # Make a list of the property names that failed.
        props = [name.split('.', 2)[1] for name in uniques]
        raise ValueError('Properties %r are not unique.' % props)

This is the only way to transactionally check the uniqueness.

https://webapp-improved.appspot.com/_modules/webapp2_extras/appengine/auth/models.html#Unique



来源:https://stackoverflow.com/questions/29820133/how-to-check-duplicate-data-in-my-datastore-and-display-the-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!