1

how are you?

I have a model that has two fields named start_time and end_time, both are CharField, and this model has a relation to another model that has a field named date it is a DateField. It looks like this

class A(models.Model):
    date = models.DateField()

class B(models.Model):
    relation = models.ForeignKey(A)
    start_time = models.CharField()
    end_time = models.CharField()

I need to query model B, using datetime values for example:

B.models.filter(reconstructed_datetime="2021-04-19 15:02:00")

where reconstructed_datetime is date (from model A) concatenated with start_time or end_time (from model B)

I tryed something like this:

        B.objects.annotate(
            reconstructed_start=Concat(
                F('relation__date'), Value(' '), F('start_date'),
                output_field=CharField()
            )
        ).annotate(
            reconstructed_start_datetime=Cast("reconstructed_start", DateTimeField()),
        )

But then I tried to filter

        .filter(reconstructed_start_datetime="2021-04-19 15:02:00")

and it does not return my database record database record

here "hora_inicio" is start_time. I suppose that use Cast does not work

So, do you know a way to concatenate those model values and then make a query as datetime field?

Jhon Sanz
  • 107
  • 1
  • 6
  • Can you provide examples of how `start_time` and `end_time` are stored? Are they ISO 8601 times? Timestamps? – elyas Apr 30 '21 at 01:11
  • Hello, Are in HH:MM:SS format, something like "hora_inicio" as shown in the last image. I am thinking that the problem is timezone. Let me check it – Jhon Sanz Apr 30 '21 at 14:33
  • The [recommendation](https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/#overview) is to store your data as UTC. Your date object would be stored as UTC by default if timezone support is enabled. – elyas Apr 30 '21 at 19:29
  • How critical is it that you use an annotation here though? You can construct a fairly simple query by splitting the input datetime into its date and time components. I can post an example, but it wouldn't be answering your specific question about concatenation – elyas Apr 30 '21 at 19:31

0 Answers0