Giulia
Giulia

Reputation: 807

How to store two Integers in one Django model instance?


Inside my Django model which is called Setup, I have an instance dedicated to the timing that the user can set in case of fast operation.

In real life, the timing is expressed by two numbers, example:
timing: 5-10 seconds
where 5 is the "pause" and 10 the "motor on" time.

Now, I know that probably the best way to have this set up is to separate the two and have one instance for each, but for usability reason I'd need to keep the "real" format, so number + hyphen + number.

Is there any way in Django to store two different numbers in the same model instance?

There will be a form for this model and ideally it should have input + hyphen + input.

fast_op_timing = models.IntegerField...??

Thank you very much in advance. I appreciate your help!

Upvotes: 0

Views: 418

Answers (1)

Stefan Collier
Stefan Collier

Reputation: 4682

two integer fields will give sort your numerical needs and overriding the str function will give you the usabillity you are looking for.

class Setup(models.Model):
    pause = models.IntegerField()
    motor = models.IntegerField()

    def user_view(self):
        return "{}-{} seconds".format(self.pause, self.motor)

    def __str__(self):
        return self.view()

Example

> my_setup = Setup(pause=5, motor=10)
> print(str(my_setup))
5-10

Upvotes: 2

Related Questions