我想把列表数据放到City& Prefecture& Area& User模型中? 我写了
book3 = xlrd.open_workbook('./data/excel1.xlsx')
sheet3 = book3.sheet_by_index(0)
data_dict = OrderedDict()
tag_list = sheet3.row_values(0)
tag_list1_user_id = tag_list[9]
fourrows = []
for row_index in range(7, sheet3.nrows):
row = sheet3.row_values(row_index)
if len(fourrows) == 5:
fourrows=[]
fourrows.append(row)
fourrows_transpose = list(map(list, zip(*fourrows)))
print(fourrows_transpose)
val3 = sheet3.cell_value(rowx=0, colx=9)
user3 = Companyransaction.objects.filter(user_id=val3)
if user3:
user3.update(XXXXX)
models.py是
class Area(models.Model):
name = models.CharField(max_length=20, verbose_name='エリア名', null=True)
class User(models.Model):
user_id = models.CharField(max_length=200,null=True)
area = models.ForeignKey('Area',null=True, blank=True)
class Prefecture(models.Model):
name = models.CharField(max_length=20, verbose_name='prefecture')
area = models.ForeignKey('Area', null=True, blank=True)
class City(models.Model):
name = models.CharField(max_length=20, verbose_name='city')
prefecture = models.ForeignKey('Prefecture', null=True, blank=True)
class Price(models.Model):
name = models.CharField(max_length=20, verbose_name='price')
PRICE_RANGE = (
('a', 'u500'),
('b', '500-1000'),
('c', 'u1000'),
)
price_range = models.CharField(max_length=1, choices=PRICE_RANGE)
city = models.ForeignKey('City', null=True, blank=True)
在print(fourrows_transpose)中,显示
[['America', '', '', '', ''], ['', '', 'u1000', '500~1000', 'd500'], ['NY', 'City A', '×', '×', '×'], ['', 'City B', '×', '×', '×'], ['', 'City C', '×', '×', '×'], ['', 'City D', '×', '×', '×'], ['', 'City E', '×', '×', '×']]
我想把'美国'放到县的area
和城市A到城市的name
和×到Price的名字。
所以,我想把这些数据tp user3.update(XXXXX)。我应该写什么给XXX?我该怎么做?
答案 0 :(得分:0)
如果您有“地区”,“城市”和“价格”的现有实例,则必须拨打每个实例并单独更新。
示例(假设用户和地区按地区属性关联):
pref = Prefecture.objects.get(area=user3.area)
city = City.objects.get(prefecture=pref)
price = Price.objects.get(city=city)
pref.name = "whatever you want"
pref.save()
city.name = "whatever you want"
city.save()
price.name = "whatever you want"
price.save()
如果您没有上述模型的现有实例,那么您必须为每个模型创建一个实例,并将它们相互链接。
示例(假设用户和地区按地区属性关联):
pref = Prefecture.objects.create(name="yourname", area=user3.area)
city = City.objects.create(name="yourname", prefecture=pref)
price = Price.objects.create(name="yourname", city=city)
希望这有帮助!