Muttiple datatime fields sort by most recent

Hi,

Im very new to Python and Django and stuck on a problem and after some help.

I have a function view that returns data from the database, this data contains 4 datetime fields all relating to different things, like startdate, enddate etc.

I have 10 entires in the database, each entry as 4 dates. The list wants to list in order the dates regardless of the entire.

MyFirstEntry
Event : DateTime
MyThirdEnrty
Event : DateTime
MyFirstEntry:
Event2 : DateTime

To get the data i have a basic function view

@login_required
def getDate(request):
    results=events.objects.all().order_by()
    return render(request,"pages/events.html",{"events":results})
    
    class Meta:
        db_table="apps_events"

Any pointers would be amazing.

Thanks

Tommy

It may be helpful if you posted the model involved here, along with a more detailed description of what you’re needing to do.

You wrote:

What do you mean by this?

Can you explain a little more about what you’re trying to accomplish?

Sorry Ken, i think the spellcheck kicked in there.

The list wants to list in order the dates regardless of the entry or row in the database.

class Events(models.Model):
    event_name = models.CharField(max_length=255, blank=False)
    event_start_date = models.DateTimeField(blank=True, null=True)
    event_midterm_date = models.DateTimeField(blank=True, null=True)
    event_end_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return str(self.Events)

Thanks for the quick reply Ken.

Should of added that i want to show this in a table in html like this:
EventName:
event_start_date : datetime
EventName
event_start_date : datetime
EventName
event_start_date : datetime

but sorted in a order of whatever the closest date is. I hope that makes sense

We’re getting closer, but I’m still not sure I’m following you.

Are you just looking to sort by event_start_date?
e.g. results = events.objects.all().order_by('event_start_date')

Or am I still missing something in what you’re asking?

So i like the table to list the closest date regardless of the event or the eventname.
So for example.
The EventNameX - Where this is the event name of the event that is closest to happening
eventEndDate : DataTime - where this is the date of the event that is closest to happening
The EventName Y
event_start_date : Datetime

Im really sorry for the rubbish examples.

The result being i can have a list the shows the dates for the eventName and the event which is happening first

I think what i need is the closeest date of any event for any event name to be listed first.

Let’s try it this way:

event_name start_date midterm_date end_date
Christmas Dec 23 Dec 25 Jan 2
Thanksgiving Nov 23 Nov 25 Nov 28
Autumn Sep 21 Nov 15 Dec 20
Fall Semester Sep 6 Nov 20 Dec 18

What would you want to see rendered for this data?
(GIven that today is Nov 5. And, would this change if today were Dec 5? Or if this were run on Sep 1?)

1 Like

Ha thanks,

So i’d like it to show
Fall Semester
Startdate : Sept 6
Autumn:
Start_Date: Sept 21
Autumn:
midterm_date : Nov 15

Oh and yes it would be only for dates that are coming up rather than past

So, for today (Nov 5) you would want to see:
Autumn
Midterm_date: Nov 15
Fall Semester
Midterm_date: Nov 20
Thanksgiving
Start date: Nov 23

Is this correct?

That is it Ken. Thanks :slight_smile:

So if my understanding is correct, your data is not structured to facilitate that type of query. If that’s the type of operation that is going to happen frequently within your application, you should probably normalize your tables.

Something like:

class Event(models.Model):
    event_name = models.CharField(max_length=255, blank=False)
    def __str__(self):
        return str(self.event_name)

class EventDateType(models.Model):
    date_order = models.IntegerField()
    date_name = models.CharField(max_length=20)

class EventDate(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    event_date_type = models.ForeignKey(EventDateType, on_delete=models.PROTECT)
    event_date = models.DateTimeField(blank=True, null=True)

You would then prepopulate the EventDateType table with data like:

date_order date_name
1 Start date
2 Midterm date
3 End date

Ok. i think i understand. I will give this a go and message back if thats ok?

1 Like

Sure - no problem.

Your alternative is to do this in your code. You could “flatten” your query response into a “list of tuples” yourself and then sort the list. (The decision between these options would be based upon how prevalent this type of operation is going to be in your application.)

Hi Ken, I’ve been playing around with this, and the more i think about my app i think im going down the wrong route.

I need to let users enter the dates via a form. And thinking about it, i dont think i want to specifiy the name of the date fields, but let the user name the date event.

So it would be more like eventName and the KeyDates, where keyDates would specifiy the event and the date/time.

Do you know if this is possible. I suppose i could split this out like you have suggested, but is it possible for a form to update different models?

Thanks

To be a bit precise, a form doesn’t update models. A form is a representation of an HTML form.
A model form is still just a form. The difference is that Django is able to automatically generate the form fields from the model - but it’s really still just a form.

So, to directly address your question, it can be handled in a number of different ways.

You can create separate model forms (one for each model) and render them all on the same page.

You can create a single generic form and split the fields to the different models yourself.

You can use features like model formsets (or inline formsets) if you have multiple instances of one of the models to be shown on the page.

Thank you Ken, you have been really helpful.

I will build this out. I still dont know how to sort in date order, but i think with this approach i hopefully can figure it out.

Thanks so much for your time.

Tom.

Hey Ken,

Im back trying to work this one out.

I have created a seperate model for the event data.

class Event(models.Model):
    event_name = models.CharField(max_length=255, blank=False)
    def __str__(self):
        return str(self.event_name)

class EventDate(models.Model):
    event = models.ForeignKey(Event, to_field='event_name', on_delete=models.CASCADE)
    event_date_name = models.CharField(max_length=20)
    event_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return str(self.event)

I have created a form and a seperate button to submit just the EventDate fields to the EventDate model.

But this doesn’t seem to work, it posts but doesn’t update the database. I’m thinking this is maybe because it can’t link the Event.event_name with the EventDate.event_date_name field.

When i view this in Django Admin and add a new entry, i get a dropdown list in the EventDate.event field, which allows me to assign the event_date to the correct Event.event_name.

I dont get this in the form. So i am thinking that do i need to make values available in the form so that i can select the Event.event_name

But this i dont know how to do, and also if i have a dropdown list taken from the values in the database, how can i add a new Event.event_name is there a way to have it show as a drop down but with a add new option?

Hope this makes sense.

Thanks

Tom

I’m most likely going to need to see the form and the view(s) associated with this to be able to offer any suggestions.

The event field in EventData should be rendered by default as a select widget.

If you want the ability to select / add, I know there are multiple ways of doing it.

  • The Select2 module allows for that feature. (Along with its companion django-select2.)
  • The Django admin has the little “+” icon next to the select box for bring up a modal form for adding a new entry.
  • You could use the datalist feature as well.