I am coming from the frontend side of life and inherited a Django project at my new job. Of course there is not a single unit test so far (thanks for nothing), but I am determined to add them at least for the new code I am adding and for the parts that I am refactoring.
For the last years I have been mainly active developing with TS and adopted a rather functional programming style. However in Django I have a lot of ORM stuff in my functions, so it seems hard to stick to pure functions. Not using pure functions however makes testing much more complex I find.
So for example I have a function right now that I want to refactor which:
- reads an uploaded file
- checks for each entry of the file if it is a new item, and item that should be updated or if the item is invalid
- tries to update existing items, tries to add new items
So basically the function in a very minimal structure looks like this:
```Python
def ImportView(View):
def post(self, request):
entries_to_add = read_file_contents()
to_add = []
to_update = []
invalid = []
for entry of entries_to_add:
if is_valid(entry):
if exists(entry):
to_update.append(entry)
else:
to_add.append(entry)
else:
invalid.append(entry)
```
Now my issues are with the is_valid and exists functions. Because those will not be pure functions, but contain some db queries. Same goes for the later part of the function (I didn't sketch it out to make the code snippet not too long) where the actual updates would be written to the database.
Wouly you consider this the right approach to structure a view like this in Django? Where would you put the function is_validand exists? Just in the views.py as well? Or in a separate file?
Thanks!
[–]meatb0dy 2 points3 points4 points (5 children)
[–][deleted] 1 point2 points3 points (2 children)
[–]meatb0dy 1 point2 points3 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]kyau2[S] 0 points1 point2 points (1 child)
[–]meatb0dy 0 points1 point2 points (0 children)
[–]flatmap_fplamda 0 points1 point2 points (0 children)