簡體   English   中英

Python-Django csv.writer

[英]Python-Django csv.writer

我如何處理 smart_str writer.writerow 中的 Nonetype?,這就是我將數據導出到 excel 的方式,

我使用了 smart_str 這是我的完整代碼,我希望這能澄清或理解我的問題,我希望這能解決問題

我有 3 個模型涉及這里

StudentsEnrollmentRecord Student_Users(field) 類名 StudentProfile 和在 StudentProfile 下我有另一個 foriegnkey Parent_Users(ParentsProfile)

def downloadcv(request):
    response = HttpResponse(content_type='text/csv')
    # decide the file name
    response['Content-Disposition'] = 'attachment; filename="StudentEnrollmentRecord.csv"'

    writer = csv.writer(response, csv.excel)
    response.write(u'\ufeff'.encode('utf8'))

    # write the headers
    writer.writerow([
        smart_str(u"students ID"),
        smart_str(u"Fullname"),
        smart_str(u"Courses"),
        smart_str(u"Strands"),
        smart_str(u"Section"),
        smart_str(u"Payment_Type"),
        smart_str(u"Discount_Type"),
        smart_str(u"Education_Levels"),
        smart_str(u"Semester"),
        smart_str(u"ESC"),
        smart_str(u"Student_Types"),
        smart_str(u"Last_School_Attended"),
        smart_str(u"Address_OF_School_Attended"),
        smart_str(u"GWA"),
        smart_str(u"School_Year"),
        smart_str(u"Birthday"),
        smart_str(u"Citizenship"),
        smart_str(u"Religion"),
        smart_str(u"Place_Of_Birth"),
        smart_str(u"Telephone_Number"),
        smart_str(u"Gender"),
        smart_str(u"Home_Address"),
        
        
        smart_str(u"Fathers_Fullname"),
        smart_str(u"Fathers_Occupation"),
        smart_str(u"Fathers Company"),
        smart_str(u"Fathers_Gmail"),
        smart_str(u"Fathers_Educational_Attainment"),
        smart_str(u"Fathers_Contact_Number"),
        smart_str(u"Fathers Landline"),

        smart_str(u"Mothers_Fullname"),
        smart_str(u"Mothers_Occupation"),
        smart_str(u"Mothers Company"),
        smart_str(u"Mothers_Gmail"),
        smart_str(u"Mothers_Educational_Attainment"),
        smart_str(u"Mothers_Contact_Number"),
        smart_str(u"Mothers_Landline"),
        
        smart_str(u"Family_Total_Income"),
        smart_str(u"Number_Of_Siblings"),
        smart_str(u"Family_Status"),
        
        smart_str(u"Guardians_Fullname"),
        smart_str(u"Guardians_Address"),
        smart_str(u"Contact_Number"),
    ])
    # get data from database or from text file....
    yearid = request.POST.get("yearid")
    print("yearid: ", yearid)
    reports = StudentsEnrollmentRecord.objects.filter(School_Year=yearid).order_by('Education_Levels','-Date_Time')
    print(reports)
    for report in reports:
        writer.writerow([
            smart_str(report.id),
            smart_str(report.Student_Users),
            smart_str(report.Courses),
            smart_str(report.strands),
            smart_str(report.Section),
            smart_str(report.Payment_Type),
            smart_str(report.Discount_Type),
            smart_str(report.Education_Levels),
            smart_str(report.Semester),
            smart_str(report.ESC),
            smart_str(report.Student_Types),
            smart_str(report.Last_School_Attended),
            smart_str(report.Address_OF_School_Attended),
            smart_str(report.GWA),
            smart_str(report.School_Year.Description),
            
            smart_str(report.Student_Users.Birthday) or "None",
            smart_str(report.Student_Users.Citizenship) or "None",
            smart_str(report.Student_Users.Religions) or "None",
            smart_str(report.Student_Users.Place_Of_Birth) or "None",
            smart_str(report.Student_Users.Landline) or "None",
            smart_str(report.Student_Users.Gender) or "None",
            smart_str(report.Student_Users.Unit_Number_Street + report.Student_Users.Barangay + report.Student_Users.City + report.Student_Users.AddressLine1) or "None",
            
            
            smart_str(report.Student_Users.Parent_Users.Fathers_Lastname + report.Student_Users.Parent_Users.Fathers_Firstname + report.Student_Users.Parent_Users.Fathers_Middle_Initial) or "None",
            smart_str(report.Student_Users.Parent_Users.Father_Occupation) or "None",
            smart_str(report.Student_Users.Parent_Users.Father_Company_Employed) or "None",
            smart_str(report.Student_Users.Parent_Users.Father_Email) or "None",
            smart_str(report.Student_Users.Parent_Users.Educational_AttainmentID_Father.Description) or "None",
            smart_str(report.Student_Users.Parent_Users.Father_MobileNo) or "None",
            smart_str(report.Student_Users.Parent_Users.Father_Landline) or "None",
            
            smart_str(report.Student_Users.Parent_Users.Mother_Maiden_LastName + report.Student_Users.Parent_Users.Mother_FirstName + report.Student_Users.Parent_Users.Mother_Middle_Initial) or "None",
            smart_str(report.Student_Users.Parent_Users.Mother_Occupation) or "None",
            smart_str(report.Student_Users.Parent_Users.Mother_Company_Employed) or "None",
            smart_str(report.Student_Users.Parent_Users.Mother_Email) or "None",
            smart_str(report.Student_Users.Parent_Users.Educational_AttainmentID_Mother.Description) or "None",
            smart_str(report.Student_Users.Parent_Users.Mother_MobileNo) or "None",
            smart_str(report.Student_Users.Parent_Users.Mother_Landline) or "None",
            
            smart_str(report.Student_Users.Parent_Users.Family_Total_Income.Description) or "None",
            smart_str(report.Student_Users.Parent_Users.numberOfSiblings) or "None",
            smart_str(report.Student_Users.Parent_Users.Family_Status.Description) or "None",
            
            smart_str(report.Student_Users.Parent_Users.Guardian_LastName + report.Student_Users.Parent_Users.Guardian_FirstName + report.Student_Users.Parent_Users.Guardian_Middle_Initial) or "None",
            smart_str(report.Student_Users.Unit_Number_Street + report.Student_Users.Barangay + report.Student_Users.City + report.Student_Users.AddressLine1) or "None",
            smart_str(report.Student_Users.Parent_Users.Guardian_MobileNo) or "None",
        ])
    return response if response is not None else 'None'

這是錯誤

在此處輸入圖片說明

完整追溯

Traceback:

File "/home/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/home/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/unidaweb/unidaproject/Homepage/views.py" in downloadcv
  389.             smart_str(report.Student_Users.Parent_Users.Guardian_LastName + report.Student_Users.Parent_Users.Guardian_FirstName + report.Student_Users.Parent_Users.Guardian_Middle_Initial) or "None",

Exception Type: TypeError at /downloadcv/
Exception Value: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

您可以使用smart_str(u"Citizenship") or "unknown"來獲得后備字符串

正如@jujule 和@May Yie 所說,實現它的最好方法是重構smart_str函數,您可以嘗試以下操作:

my_var_to_return = None|'string' 
return my_varto_return if my_var_to_return is not None else 'Something else'

重要的一件事是,您將阻止錯誤在使用smart_str函數的任何視圖中傳播。

如果您無法控制smart_str您可以創建一個名為super_smart_str(mystr)的函數,您可以執行以下操作:

def super_smart_str(mystr):
    my_str = smart_str(mystr)
    return my_str if my_str is not None else 'Something else'

然后你可以自定義這個:

# write the headers
writer.writerow([
    super_smart_str(u"Birthday"),
    super_smart_str(u"Citizenship"), # Will not return None values
    super_smart_str(u"Religion"),
])

最后你正在處理你的串聯:

last_name = report.Student_Users.Parent_Users.Guardian_LastName or "Anything else"
first_name = report.Student_Users.Parent_Users.Guardian_FirstName or "smt else" 
initial = report.Student_Users.Parent_Users.Guardian_Middle_Initial or "other thing"
smart_str( last_name + first_name +  initial) # Should not get any errors

而已。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM