2017-08-01 68 views
0

我正在嘗試使用循環以某種方式填充模型的填充腳本。下面是代碼可能看起來像:使用循環在Django中填充模型

models.py

class ExampleModel(models.Model): 
    name = models.CharField(max_length=32) 
    code = models.CharField(max_length=3) 
    description = models.TextField(max_length=128) 

的text.txt

001 Name One 
    Description one 
    Description one line two 
023 Name Two 
    Description two 
    Description two line two 
    Description two line three 
AAA Name Three 
BBB Name Four 
    Description three 

populate.py

def populate(): 
    with open("text.txt") as f: 
     content = f.readlines() 

    for line in content: 
     fields = line.split(' ', 1) 
     if len(fields[0]) == 3 and (fields[0].strip().isupper() or fields[0].strip().isdigit()): 
      code = fields[0].strip() 
      name = fields[1].strip() 
      print("%s-%s" % (code, name)) 
      add_object(name=name, code=code) 

def add_object(name, code, periship_amount): 
    f = ExampleModel.objects.get_or_create(name=name, code=code)[0] 
    return f 

if __name__ == '__main__': 
    populate() 

眼下,人口腳本取任何以三個字符的字符串開頭的行,並將它分成兩行,將三個字符的字符串寫入代碼和其餘的字符串變成了名字。我想要做的是將整個文本(帶有描述的文本)放在一個代碼行下方,並在另一個之上,以等於上面的代碼名稱的描述字段。有誰知道如何在populate.py中編寫該循環?謝謝。

回答