Using queries

For the District and County data tables, a final wrinkle is added, querying against the newly added state data to find the associated state by FIPS code. By querying the State class using session.query and filtering the state's data using the filter_by method (passing the FIPS code from the district records as the filter argument), and then specifying that the first result should be used, the correct state can be called. The variable state's id field is used to populate the district's state_id column to create the relationship:

# This uses the STFIPS data to query the State table and find the state
for count, record in enumerate(district_records):
district = District()
district.district = record[0]
district.name = record[1]
state = session.query(State).filter_by(statefips=record[4]).first()
district.state_id = state.id
dist_geo = district_shapes[count]

gshape=pygeoif.MultiPolygon(pygeoif.geometry.as_shape(dist_geo))
district.geom = 'SRID=4326;{0}'.format(gshape.wkt)
session.add(district)
if count % 50 == 0:
session.commit()
session.commit()

The County table is similarly looped and also includes a State query. Check the script to see the completed code. Once all of the data has been written to the data tables, close the session and dispose of the connection engine:

 session.close()
engine.dispose()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset