Alihaydar Gubatov
Alihaydar Gubatov

Reputation: 1045

How to create custom django model field for representing opening and closing hours of a place

I have an application about Restaurants. You can set its opening and closing time. I do it by adding two time fields like this.

class Place(models.Model):
    # other fields
    opening = models.TimeField()
    closing = models.TimeField()

However I want to do it with one, custom field something like this.

class Place(models.Model):
    # other fields
    operating_hours = models.DualTimeField()

Upvotes: 1

Views: 496

Answers (1)

rollinger
rollinger

Reputation: 541

1) Use a CharField and parse the string in the model via a property, e.g "hh:mm - hh:mm"

2) Use a the Django native DurationField: https://docs.djangoproject.com/en/1.10/ref/models/fields/#durationfield if you want to model opening hours you need a second field to define the opening hour, it is working on the timedelta.

3) Use two TimeFields like every one else would do.

4) Another option would be a MultiSelectField where the user can select the hours of the day the place is open.

OPENING_HOURS = (
    (1,'1am'),
    (2,'2am'),
    (3,'3am'),
    (4,'4am'),
    ...
    (12,'12pm'),
)

class Place(models.Model):
    # other fields
    operating_hours = models.my_field = MultiSelectField( choices=MY_CHOICES)

See: https://pypi.python.org/pypi/django-multiselectfield

Upvotes: 1

Related Questions