jan biel
jan biel

Reputation: 45

Simple operations with data requested from a Django model

I am trying to write a simple web application, where i can upload csv files and return the headers from each file. Everything is working fine. The id, the path to the file, gets saved in a database.

This is the response i am getting:

{
"id": 1,
"filefield": "http://127.0.0.1:8000/api/merged/1/uploads/header_body_test_zZr4Cea.csv"
}

What i do not understand is, where or how can i actually work with the data i request from the database? What i am imagining is a different url route, where i can specify an id and the response would be something like this:

{
"id": 1,
"filefield": "http://127.0.0.1:8000/api/merged/1/uploads/header_body_test_zZr4Cea.csv"
"headers_of_csv": "Date;Amount"
}

Its hard for me to explain (or google) what my problem actually is. I dont understand where or how the code to do this would actually be (is it part of the serializer, or the view, or in the model?).

Or even in simpler terms, lets say i have a model, that had an id and a 3 digit number and returns this:

{
"id": 1,
"number": 567
}

How or where could i create a respone like this:

{
"id": 1,
"number": 567
"first_digit_or_number": 5
}

Any help is greatly appreciated, i just dont understand what i am supposed to be looking for.

Upvotes: 1

Views: 64

Answers (1)

MrName
MrName

Reputation: 2529

Let's start with your simpler question. You have the model from your example:

class MyModel(models.Model):
    number = models.IntegerField()

You then create an instance of this model by sending a POST request, which results in the following object:

{
    "id": 1,
    "number": 567
}

Now you want to return some additional information about this object, which at least in this case, is not stored in the database, but rather is derived from other information about the object. This is where model properties come in handy.

class MyModel(models.Model):
    number = models.IntegerField()

    @property
    def first_digit_of_number(self):
        return int(str(self.number)[0])

Note that if you are using django rest framework, you will need to manually add this field to your serializer.

Getting back to the example of your CSV file, this means that you could add a headers_of_csv property to your model, which would contain code to introspect the file and return the headers.

Depending on your use case though, there is a potential performance issue here. If you want to expose this property on your list view (i.e. - GET /thing/ and not GET /thing/{id}/), you could end up opening thousands of files to accommodate a single request (since the information is generated dynamically every time). This does not make much sense, since the information will only change if the CSV file changes. In this case, you could consider adding headers_of_csv as an actual database column, and populate it when a model gets saved.

Upvotes: 1

Related Questions