[Fixed]-Replace database value when recalling in Django

1๐Ÿ‘

I understand you want to transform values on the fly (On => 1, Off => 0).

As you want to transform the values for display purposes only, you have several options to deal with that (none will change the data in DB):

1a. transform values in the custom SQL query using Custom Manager in models.py
โ€“ https://docs.djangoproject.com/en/1.9/topics/db/managers/#adding-extra-manager-methods

1b. transform values in the custom raw SQL in your views
โ€“ https://docs.djangoproject.com/en/1.9/topics/db/sql/#adding-annotations

  1. add derived attribute in your model class using Model Method in models.py

  2. transform values in the view.py code generating the proper values for context in templates

  3. transform values in the template code

Where you do that depends on whether and where you want to use the original on/off values and where you want to put the transformation workload.

If you do not need the original values to be processed in Django, then change them on the database level (in the read query), so Django already receives the 0/1 values.

However you might find it easiest to follow option 2 (in models.py).

class Item1(models.Model):
    ... your current definitions

    def _bin_value(self):
        "Returns the tranformed ON/OFF value to 0/1."
        if self.value == "ON":
             return 1 
        if self.value == "OFF":
             return 0 
        return None # you should define how you handle empty, NULL or unexpected value
    bin_value = property(_bin_value)

And use bin_value in your views instead of value.

๐Ÿ‘คRadek

0๐Ÿ‘

Item1.objects.all() returns a queryset (very similiar to a list) containing all the Item objects. The actual Item1 class just takes the place of a table in a database. Doing Item1.objects.all()[0] will give you the first item object in the queryset. You can also use the .order_by method on a queryset to order it by a specific value, such as date or a vote value. Also, after you operate on a database object, you need to save it. So say you have this code:

items = Item1.objects.all()

Then youโ€™d do

for item in items:
    if item.value == 'OFF':
        item.other_value == 1
    item.save()
๐Ÿ‘คDorian Dore

Leave a comment