Beispiel #1
0
def export_csv(stream, queryset):
    """
    Export the given ``QuerySet`` as comma-separated values to a stream.

    Args:
        stream: A ``file``-like object with a ``write`` method.
        queryset: A Django ``QuerySet`` of instances to export.

    Returns:
        `None`. Has a side effect of writing to the ``stream``.
    """
    concrete_fields = get_concrete_fields(queryset.model)
    field_names = [unicode(field.get_attname()) for field in concrete_fields]

    writer = csv.writer(stream, encoding='utf-8')
    writer.writerow(field_names)

    for instance in queryset.iterator():
        row = [getattr(instance, field_name) for field_name in field_names]
        row = [unicode(cell) if cell is not None else '' for cell in row]
        writer.writerow(row)
Beispiel #2
0
def export_excel(stream, queryset):
    """
    Export the given ``QuerySet`` as an Excel spreadsheet.

    Args:
        stream: A ``file``-like object with a ``write`` method.
        queryset: A Django ``QuerySet`` of instances to export.

    Returns:
        `None`. Has a side effect of writing to the ``stream``.
    """
    concrete_fields = get_concrete_fields(queryset.model)
    field_names = [unicode(field.get_attname()) for field in concrete_fields]

    workbook = Workbook(write_only=True)
    worksheet = workbook.create_sheet(queryset.model.__name__)
    worksheet.append(field_names)

    for instance in queryset.iterator():
        row = [getattr(instance, field_name) for field_name in field_names]
        worksheet.append(row)

    workbook.save(stream)
Beispiel #3
0
def select_fields_for_export(model):
    concrete_fields = get_concrete_fields(model)
    return [
        unicode(field.name) for field in concrete_fields if field
        if not isinstance(field, OneToOneRel)
    ]