Luke Plant avatar Luke Plant committed bd25a0c

Added support for Field.choices

Comments (0)

Files changed (5)


             source = self.faker.lorem
         return self.get_allowed_value(source, field)
+    def choice(self, field=None):
+        assert field is not None, "The field parameter must be passed to the 'choice' method."
+        choices = [c[0] for c in field.choices]
+        source = lambda: random.choice(choices)
+        return self.get_allowed_value(source, field)
     ## Other attributes provided by 'Faker':
     # username


     if isinstance(field, EmailField):
         return '"email"'
+    # Use choices, if available.
+    choices = getattr(field, 'choices', None)
+    if choices is not None and len(choices) > 0:
+        return '"choice"'
     field_type = field.get_internal_type()
     if field_type == "CharField" or field_type == "TextField":
         # Guess by the name


 the original. If the original often takes a standard form (e.g. a single word
 'yes' or 'no'), this could easily fail to hide the original data.
+choice = lambda anon, obj, field, val: anon.faker.choice(field=field)
+choice.__doc__ = """
+Randomly chooses one of the choices set on the field.


         ('icon', UNKNOWN_FIELD),
         ('some_datetime', "datetime"),
         ('some_date', "date"),
+        ('sex', "choice"),
         self.assertEqual(mod.strip(), expected.strip())
+                                                          sex='X',
     def test_eveything(self):
                 ('age', "positive_small_integer"),
                 ('some_datetime', "datetime"),
                 ('some_date', "date"),
+                ('sex', "choice"),
             # is first in the list, as recommended and as introspection
             # generates.
+            # test for DjangoFaker.choice
+            self.assertTrue( in ('M', 'F'))


     icon = models.ImageField(upload_to='.')
     some_datetime = models.DateTimeField()
     some_date = models.DateField()
+    sex = models.CharField(max_length=1, choices=[('M', 'Male'),
+                                                  ('F', 'Female')])
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.