我正在尝试在循环中保存多个对象。
for i in range(0,12):
some_url = "blabla.com/signnum=" + str(i)
req = urllib2.Request(astro_url,headers=hdr)
str_response = urllib2.urlopen(req)
json_str = json.load(str_response)
with transaction.atomic():
if i == 0:
capricorn, cp_created = Capricorn.objects.get_or_create(astro_date=json_str['daily']['data_date'],
defaults={
'headline': json_str['daily']['headline'],
'headcontent':json_str['daily']['content'],
'rating':json_str['daily']['rating'],
'love_rate':json_str['daily']['love'],
})
if cp_created:
print 'Capricorn saved'
else:
print 'Capricorn is already in db'
if i == 1:
#different model
if i == 2:
#different model
....
....
这一直持续到12个。相同的字段只有不同的型号名称。
我遇到的问题是最后的第12个对象没有被插入db,尽管
if last_created:
print last_createdobj.id
print 'LastModelObject saved'
else:
print 'LastModelObject is already in db'
正在打印1
和LastModelObject saved
。正在插入所有其他对象。
这里发生了什么?循环真的循环了12次。写入db是原子的。什么可以在这里变坏?我真的被卡住了..
我正在使用sqlite(dev)并且它正在打印db中不存在的id 1
,这到底是什么?
答案 0 :(得分:1)
我建议改变模型结构,而不是12个if语句和12个不同的模型。 Something like this:
#models.py
CAPRICORN = 'Capricorn'
AQUARIUS = 'Aquarius'
PISCES = 'Pisces'
ARIES = 'Aries'
TAURUS = 'Taurus'
GEMINI = 'Gemini'
CANCER = 'Cancer'
LEO = 'Leo'
VIRGO = 'Virgo'
LIBRA = 'Libra'
SCORPIO = 'Scorpio'
SAGITTARIUS = 'Sagittarius'
SIGN_CHOICES = (
(1, CAPRICORN,
2, AQUARIUS,
3, PISCES,
4, ARIES,
5, TAURUS,
6, GEMINI,
7, CANCER,
8, LEO,
9, VIRGO,
10, LIBRA,
11, SCORPIO,
12, SAGITTARIUS)
)
class Sign(models.Model):
signtype = models.CharField(choice=SIGN_CHOICES)
astro_date = models.DateField()
headline = models.CharField(max_length=255)
headcontent = models.TextField()
rating = RatingField()
love_rate = models.CharField(max_length=255)
在视图中,您只需将index+1
分配给signtype
,get_or_create
就可以正常使用。
示例:
astro_date = json_str['daily']['data_date']
sunsign, created = Sign.objects.get_or_create(signtype=index+1, astro_date=astro_date,
defaults={
'headline': json_str['daily']['headline'],
'headcontent':json_str['daily']['content'],
'rating':json_str['daily']['rating'],
'love_rate':json_str['daily']['love'],
})
这样,您的代码更清晰,更易于调试。