Write a QuerySet or ValuesListQuerySet to a CSV file

    based on djangosnippets by zbyte64 and http://palewi.re

    Arguments:
        qs (QuerySet or ValuesListQuerySet): The records your want to write to a text file (UTF-8)
        filename (str): full path and file name to write to

def write_queryset_to_csv(qs, filename):
    """Write a QuerySet or ValuesListQuerySet to a CSV file

    based on djangosnippets by zbyte64 and http://palewi.re

    Arguments:
        qs (QuerySet or ValuesListQuerySet): The records your want to write to a text file (UTF-8)
        filename (str): full path and file name to write to
    """
    model = qs.model
    with open(filename, 'w') as fp:
        writer = csv.writer(fp)
        try:
            headers = list(qs._fields)
        except:
            headers = [field.name for field in model._meta.fields]
        writer.writerow(headers)

        for obj in qs:
            row = []
            for colnum, field in enumerate(headers):
                try:
                    value = getattr(obj, field, obj[colnum])
                except:
                    value = ''
                if callable(value):
                    value = value()
                if isinstance(value, basestring):
                    value = value.encode("utf-8")
                else:
                    value = str(value).encode("utf-8")
                row += [value]
            writer.writerow(row)