1

In my django model I am trying to set fields like this:

mouth = models.DecimalField(choices=SCALE, max_digits=2, decimal_places=1)
nose = models.DecimalField(choices=SCALE, max_digits=2, decimal_places=1)
persistance = models.DecimalField(choices=SCALE, max_digits=2, decimal_places=1)
rating = models.DecimalField(choices=SCALE, max_digits=2, decimal_places=1)

the choices are defined globally like this:

SCALE = ( (0.5*x, str(0.5*x)) for x in xrange(1,11) )

I register these fields in my admin.py file. The problem I have is that only the first field that is defined (in this case mouth), will display the choices list. The other ones wont display any list at all. The same scenario happens when I create a ModelForm instance and output it into a template: I dont get the list for the other fields.

Also if I try to inverse the order of the fields, It is still the first one that is displayed correctly, so it's not something related to the mouth field itself.

Is there an option I need to pass to make the fields more 'distinct'?

1
  • @Liarez: this is a generator expression. Commented Oct 14, 2013 at 12:33

1 Answer 1

3

In your definition, SCALE is a generator expression, not a sequence, so the generator is very probably exhausted after the first iteration (on your first field using it). Try using a list comprehension instead, ie SCALE = [(0.5*x, str(0.5*x)) for x in xrange(1,11)]

Sign up to request clarification or add additional context in comments.

2 Comments

Yes indeed! I guess this is also why it is suggested to define choices inside the model class so it's less likely to exhaust the generator if you reuse it for other fields.
Making a generator a class attribute won't change anything - once a generator is exhausted, it's exhausted, period. The reasons why it's (usually) better to define choices in the model is mainly locality and cohesion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.