feat: export (WIP)

This commit is contained in:
Herculino Trotta
2025-02-18 19:55:12 -03:00
parent ebc41a8049
commit 3080df9b66
17 changed files with 105 additions and 2 deletions
View File
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+6
View File
@@ -0,0 +1,6 @@
from django.apps import AppConfig
class ExportConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "apps.export_app"
+3
View File
@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.
@@ -0,0 +1,39 @@
from import_export import fields, resources
from apps.export_app.widgets.foreign_key import AutoCreateForeignKeyWidget
from apps.export_app.widgets.many_to_many import AutoCreateManyToManyWidget
from apps.transactions.models import (
Transaction,
TransactionCategory,
TransactionTag,
TransactionEntity,
)
class TransactionResource(resources.ModelResource):
account = fields.Field(
attribute="account",
column_name="account",
widget=AutoCreateForeignKeyWidget("accounts.Account", "name"),
)
category = fields.Field(
attribute="category",
column_name="category",
widget=AutoCreateForeignKeyWidget(TransactionCategory, "name"),
)
tags = fields.Field(
attribute="tags",
column_name="tags",
widget=AutoCreateManyToManyWidget(TransactionTag, field="name"),
)
entities = fields.Field(
attribute="entities",
column_name="entities",
widget=AutoCreateManyToManyWidget(TransactionEntity, field="name"),
)
class Meta:
model = Transaction
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+6
View File
@@ -0,0 +1,6 @@
from django.urls import path
import apps.export_app.views as views
urlpatterns = [
path("export/", views.export, name="export"),
]
+9
View File
@@ -0,0 +1,9 @@
from django.shortcuts import render
from apps.export_app.resources.transactions import TransactionResource
# Create your views here.
def export(request):
dataset = TransactionResource().export()
print(dataset.csv)
@@ -0,0 +1,11 @@
from import_export.widgets import ForeignKeyWidget
class AutoCreateForeignKeyWidget(ForeignKeyWidget):
def clean(self, value, row=None, *args, **kwargs):
if value:
try:
return super().clean(value, row, **kwargs)
except self.model.DoesNotExist:
return self.model.objects.create(name=value)
return None
@@ -0,0 +1,21 @@
from import_export.widgets import ManyToManyWidget
class AutoCreateManyToManyWidget(ManyToManyWidget):
def clean(self, value, row=None, *args, **kwargs):
if not value:
return []
values = value.split(self.separator)
cleaned_values = []
for val in values:
val = val.strip()
if val:
try:
obj = self.model.objects.get(**{self.field: val})
except self.model.DoesNotExist:
obj = self.model.objects.create(name=val)
cleaned_values.append(obj)
return cleaned_values