0

I'm hoping this has been done before - essentially, and hopefully I explain this correctly, what I'd like is a model with some choices (as below).

I want to circumnavigate the 'choices' must be an iterable containing (actual value, human readable name) tuples error when adding a third or fourth value to the choice tuple for a model.

Those choices not only effect directly the field for which you're selecting from, but also another few fields. I've seen things where the slug field is auto populated from e.g., a blog post title, but does any method exist for tying multiple fields to a certain choice?

class Location(models.Model):

  SERVICE_CHOICES = (
    ('bus_station', 'Bus Station', '#cdcdcd'),
    ('cafe', 'Café', '#cdcdcd'),
    ('cinema', 'Cinema', '#cdcdcd'),
    ('gardens', 'Public Gardens', '#cdcdcd'),
    ('library', 'Library'),
    ('public_services', 'Public Services'),
    ('railway_station', 'Railway Station'),
    ('restaurant', 'Restaurant'),
    ('school', 'School'),
    ('shop', 'Shop'),
    ('supermarket', 'Supermarket'),
    ('tourist_attractions', 'Tourist Attractions'),
    ('transit_station', 'Transit Station'),
    ('walks', 'Walks'),
    ('woodland', 'Woodland'),
  )

  locale_descriptor = models.CharField("Locale Descriptor", max_length=50, default='')
  latitude = models.DecimalField("Latitude", max_digits=10, decimal_places=7)
  longitude = models.DecimalField("Longitude", max_digits=10, decimal_places=7)
  title = models.CharField("Title", max_length=60, default='')
  description = models.TextField("Description")
  service_type = models.CharField("Service Type", max_length=80,choices=SERVICE_CHOICES, default='public_service')

Would anyone know how to auto populate a field dependent on these choices??

1 Answers1

0

I'm not getting a perfectly clear picture of what you're trying to do, but it sounds like what you need is a ForeignKey relationship instead of trying to augment the choices tuple. Something like this:

class ServiceType(models.Model):
    def __unicode__(self):
        return self.service_name

    service_name = modes.CharField(max_length=80)
    color = modes.CharField(max_length=7)


class Location(models.Model):
    locale_descriptor = models.CharField("Locale Descriptor", max_length=50, default='')
    latitude = models.DecimalField("Latitude", max_digits=10, decimal_places=7)
    longitude = models.DecimalField("Longitude", max_digits=10, decimal_places=7)
    title = models.CharField("Title", max_length=60, default='')
    description = models.TextField("Description")
    service_type = models.ForeignKey(ServiceType)

Not sure how you want to affect the other fields, but this can be done by overwriting the save() method or implementing a clean() method. One example: "Django. Override save for model".

Travis
  • 1,998
  • 1
  • 21
  • 36