Login

Handling choices the right way

Author:
mallipeddi
Posted:
November 2, 2007
Language:
Python
Version:
.96
Tags:
models admin choices
Score:
2 (after 2 ratings)

This solves the problem with choices described here

Define your choices like this (in models.py):

statuses = MyChoices(BIDDING_STARTED=10, BIDDING_ENDED=20)

And then:

status = models.IntegerField(
                   default=statuses.BIDDING_STARTED,
                   choices=statuses.get_choices()
                )
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyChoices:
   def __init__(self, **entries):
       self.__dict__.update(entries)
       self.choices = [ ]
       for val in entries.values():
           for key in entries.keys():
               if entries[key] == val:
                   self.choices.append((val, key))

      def get_choices(self):
          return self.choices

More like this

  1. "Magic Link" Management Command by webology 3 weeks, 4 days ago
  2. Closest ORM models to a latitude/longitude point by simonw 3 weeks, 4 days ago
  3. Log the time taken to execute each DB query by kennyx46 3 weeks, 4 days ago
  4. django database snippet by ItsRLuo 1 month ago
  5. Serialize a model instance by chriswedgwood 1 month, 4 weeks ago

Comments

tomzee (on December 29, 2007):

Here is a similar solution which allows you to pass dictionaries to the constructor, and inserts the key/value pairs into the choice-list in the same manner they are in the dictionaries.

class ChoiceMap:
    def __init__(self, *args, **entries):
        self.choices = []
        def add_choices(d):
            self.__dict__.update(arg)
            for key, val in d.iteritems():
                self.choices.append((key, val))
        for arg in args:
            if isinstance(arg, dict):
                add_choices(arg)
        add_choices(entries)
    def get_choices(self):
        return self.choices

#

Please login first before commenting.