Simple Operations With Data Requested From A Django Model
Solution 1:
Let's start with your simpler question. You have the model from your example:
classMyModel(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.
classMyModel(models.Model):
number = models.IntegerField()
@propertydeffirst_digit_of_number(self):
returnint(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.
Post a Comment for "Simple Operations With Data Requested From A Django Model"