python ORM表插入0而不是none

时间:2015-11-24 06:54:15

标签: python flask-sqlalchemy

这是我的大部分代码。我真正的问题是在models.py,countCurrentOccupancy()中:我有一个解决方法,当创建一个新的Shelter时,我需要current_occupancy为0。有没有更好的方法呢?默认值似乎不起作用,从views.py传递0似乎也不起作用。也不在methods.py中插入0。

dbsetup.py

class Shelter(Base):
    """Connects to the Shelter table
    """
    __tablename__ = 'shelter'

    shelter_id = Column(Integer, primary_key = True)
    name = Column(String(50), nullable = False)
    address = Column(String(30))
    city = Column(String(20))
    state = Column(String(13))
    zipCode = Column(Integer(5))
    website = Column(String)
    maximum_capacity = Column(Integer, nullable = False)
    current_occupancy = Column(Integer, default = '0')
    remaining_spaces = Column(Integer)

models.py:

def createShelter(new_shelter):
    newShelter = Shelter(
        name = new_shelter['name'],
        address = new_shelter['address'],
        city = new_shelter['city'],
        state = new_shelter['state'],
        zipCode = new_shelter['zipCode'],
        website = new_shelter['website'],
        maximum_capacity = new_shelter['maximum_capacity'],
        current_occupancy = 0)
    session.add(newShelter)
    session.commit()

#This method returns current_occupancy from the Shelter table as a list of only current_occupancy values
def countUpdatedOccupancy():
    p = session.query(Shelter.shelter_id, Shelter.current_occupancy)
    w = []
    for row in p:
        w.append(row[1])
    return w
#This method updates Shelter.current_occupancy with the countCurrentOccupancy().
def updateCurrentOccupancy():
    counts_list = countCurrentOccupancy()
    counts_dict = dict(counts_list)
    shelters = session.query(Shelter)
    for shelter in shelters:
        shelter.current_occupancy = counts_dict.get(shelter.shelter_id)
        co = 0
        if shelter.current_occupancy is None:
            co = 0
        else:
            co = shelter.current_occupancy
        shelter.remaining_spaces = shelter.maximum_capacity - co
        session.add(shelter)
    session.commit()

的观点:

@app.route('/shelters/shelternew', methods = ['GET','POST'])
def shelterNew():
    form = forms.ShelterForm()
    if request.method == "POST":
        new_shelter = {
            'name': form.name.data,
            'address': form.address.data,
            'city': form.city.data,
            'state': form.state.data,
            'zipCode': form.zipCode.data,
            'website': form.website.data,
            'maximum_capacity': form.maximum_capacity.data}
        models.createShelter(new_shelter)
        flash('A new shelter has been opened!')
        return redirect(url_for('shelters'))
    else:
        return render_template('shelterNew.html', form = form)

0 个答案:

没有答案