paulocheque / django-dynamic-fixture

A complete library to create dynamic model instances for testing purposes.
http://django-dynamic-fixture.readthedocs.io/
Other
391 stars 67 forks source link

Fix picking the value for a field when using grouped field choices #22

Closed sjhewitt closed 11 years ago

sjhewitt commented 11 years ago

If you have grouped the choices for a field, then the label of the first group is picked, rather than the first valid option. This change updates DynamicFixture to pick the first option from the flattened list of field options (i.e. field.flatchoices rather than field.choices)

paulocheque commented 11 years ago

Nice! I did not test it yet. Are you sure the field.flatchoices[0][0] indexes are ok?

paulocheque commented 11 years ago

Also, we need to check if there is some incompatibility issue with older versions of Django, like 1.2. Did you check that?

sjhewitt commented 11 years ago

flatchoices is a list created from field.choices, and guaranteed to be a list of 2-tuples, you can see how it is built here: https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L453

It was added in 2008, (https://github.com/django/django/commit/661f62be3c5f810fddd3b33bcbdfe33a3077a66d) which is pre-1.2, however I haven't run the test cases against 1.2. I'll try them now!

sjhewitt commented 11 years ago

Tests all pass against django==1.2.7

paulocheque commented 11 years ago

Nice! It is included in the travis script and it passes! I am just curious about the [0][0] indexes, but I will merge this pull request later. thanks!

sjhewitt commented 11 years ago

choices can be a list of tuples:

choices=(('a', 'A'), ('b', 'B'))

or a can contain a group header for sub-lists:

choices=(('Group Header', (('a', 'A'), ('b', 'B')), )

field.flatchoices flattens both the above choices into the same lists, so the [0][0] index is just used to pick the first valid choice in the list. When using grouped choices field.choices[0][0] would return 'Group Header' which is an invalid choice, but field.flatchoices[0][0] returns the first value from the first group ('a') which is a valid choice.

paulocheque commented 11 years ago

Nice! thanks a lot for your time!