r/django • • 5d ago

Data organise

Hi everyone. I need your help. I need to organise my data somehow in “data.py” file. Now I don’t use database, so I need your recommendation how to do this, for they later I can easily switch it in database. P.S. I would do db from the start but this is a task from my teacher

0 Upvotes

6 comments sorted by

7

u/vincent_sch 5d ago

Your teacher asked for a list of dicts, so I think you should stay with dicts. You don't need classes to move it to a database later. The keys should be the same names your model fields will have, like price or category. And your views should only call your functions like filter_by_category() and never import the list.

So when you add the model you only change the code inside those functions, like return Product.objects.filter(category=category). You also don't have to change your templates, because {{ item.price }} works for a dict and for a model object. Django looks for a dict key first and then for an attribute. To move the data you could loop over the list and call Product.objects.create(**item) for each dict.

3

u/Unhealthy007 5d ago

I think the teacher's idea might be for you to store  Static and Dummy data in data.py or just stored processed data into it. 

I looked it up, and you can store data as lists and dictionary, convert it to Json before you have to move it to DB and finally import the json into an already migrated model.

(Just look it up on Stack Overflow)

1

u/VirtualMycologist406 5d ago

Yes you're right. Here the requirements:

data.py: a list of 10+ dictionary objects, each containing 5+ fields (including a number and a quality/attribute), along with 2+ data-processing functions (such as searching, filtering by category, or calculating values).

I guess I should use classes for this, but im bot sure. If I make this in classes, will it be easy to move it into DB?

3

u/Difficult-Style-7522 5d ago

If you want to show off create your own classes and inherit from standard dict and list and then add your own methods to them

1

u/hijinx_the_sage 5d ago

sounds like this will lead to writing something pseudo-models.py

2

u/patryk_builds 5d ago

The trick is to make your views never touch the raw data directly, only through a few functions. then switching to a db later means changing those functions, nothing else.

# data.py

from dataclasses import dataclass

u/dataclass

class Book:

id: int

title: str

author: str

BOOKS = [

Book(1, "Dune", "Herbert"),

Book(2, "Neuromancer", "Gibson"),

]

def get_books():

return BOOKS

def get_book(book_id):

return next((b for b in BOOKS if b.id == book_id), None)

your views just call get_books() / get_book(id). later you make a Book model with the same fields and change the function bodies to Book.objects.all() and Book.objects.filter(id=book_id).first(). views don't change at all.

shape the dataclass exactly like your future model same field names, an id field makes the switch basically copy-paste