コード例 #1
0
        def write_field_data_to_db(field_name, field_data):
            for country_name in field_data.keys():

                # get country if it exists; create it if it doesn't.
                country_slug = slugify(country_name)
                try:
                    country = Country.objects.get(url_name=country_slug)
                except Country.DoesNotExist:
                    country = Country(url_name=country_slug)
                    country.CIAWFB_name_short = country_name
                    country.save()

                # Get CIA WFB Entry if it exists; create it if it doesn't.
                try:
                    CIAWFB_object = CIAWFBEntry.objects.get(country__id=country.id)
                except CIAWFBEntry.DoesNotExist:
                    CIAWFB_object = CIAWFBEntry(country=country, date_entered=timezone.now())
                    CIAWFB_object.save()

                # Now update the field we've got for that CIAWFB entry
                db_name = slugify(field_name).replace('-', '_')

                try:
                    setattr(CIAWFB_object, db_name, field_data[country_name])
                    CIAWFB_object.save()
                except DatabaseError:
                    print('Unable to write field "%s" (country "%s"). Size to write was %s.' %
                          (db_name, country_name, len(field_data[country_name])))
                    longest_field = 0
                    for cname in field_data.keys():
                        len_data = len(field_data[cname])
                        if len_data > longest_field:
                            longest_field = len_data
                    print("Field: %s; Max Length: %s" % (field_name, longest_field))
                    raise DatabaseError