S
S
s1vemod2021-08-05 21:44:15
Django
s1vemod, 2021-08-05 21:44:15

How to check a span of time in Django?

Good afternoon.
Suppose I have a model, it has two fields start , end - TimeField .

I receive a request with the same data start , end , I need these start and end not to enter the time interval of all other objects of this model.

That is, if there is an object with such data: "13:00-14:30", then an object with such data: "12:30-13:30" cannot be created.
It should be noted that the object with "13:00-14:30" cannot be created either.

How can I make it look nice?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-08-07
@s1vemod

s1vemod you can implement this only through form validation, for example like this

class MyModel(models.Model):
    start = models.TimeField(null=True)
    end = models.TimeField(null=True)

class MyForm(forms.Form):
    start = forms. TimeField(required=True)
    end = forms. TimeField(required=True)

    def clean(self):
        cleaned_data = super().clean()
        start = cleaned_data.get("start")
        end = cleaned_data.get("end")

        check =  MyModel.objects \
            .filter(
                Q(start__in=[start, end]) | (Q(end__in=[start, end])
            ).exists():
        if check:
            raise forms.ValidationError('error')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question