DateTimeField queryset returning None in Django
django model functions
django datefield vs datetimefield
django datetimefield format
django model choice field
I am trying to create a queryset for getting the values of a DateTimeField which is DATETIME in the DB.
The class in models.py:
class ChangeMetrics(models.Model): id = models.IntegerField(primary_key=True) file_id = models.ForeignKey(File, db_column = 'file_id') version_id = models.ForeignKey(Version, db_column = 'version_id') function_id = models.ForeignKey(Function, blank=True, db_column = 'function_id') date = models.DateTimeField(blank=True, null=True) user = models.TextField(blank=True) changed = models.IntegerField(blank=True, null=True)
The field in the DB:
The tuples are populated in the database and running SQL queries directly on the DB is working perfectly.
This is the queryset I am currently using in Django:
queryset = ChangeMetrics.objects.filter(~Q(changed=None), ~Q(date=None), ~Q(version_id=None))
I have tried a raw query and also a version of the query that uses exclude(), but that still returns None for date.
I am accessing the entries in the queryset through a for loop and simply accessing date through entry.date inside the for loop.
Edit: Django version 1.6.5 I have also tried getting the values through the Django shell, to no success.
Any ideas on what could be wrong?
not sure if you were able to figure this out, but I just had this problem and was able to fix it.
So, Django migrations were creating the column in the DB as datetime(6) instead of datetime. This was causing the Django models to fail to instantiate the Datetime object.
ALTER TABLE `my_table` MODIFY COLUMN `created` datetime NOT NULL
After running that if fixed my issue. Maybe in your case you could try modifying to datetime(6) instead.
QuerySet API reference | Django documentation, Also note that even though slicing an unevaluated QuerySet returns another class QuerySet (model=None, query=None, using=None, hints=None)¶ Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello'). This is the queryset I am currently using in Django: queryset = ChangeMetrics.objects.filter(~Q(changed=None), ~Q(date=None), ~Q(version_id=None)) I have tried a raw query and also a version of the query that uses exclude(), but that still returns None for date. I am accessing the entries in the queryset through a for loop and simply
We had this same issue popup while pushing code from local environment (Mac OS X) up to App Engine. While altering the fields like Alexander mentioned to be DATETIME instead of DATETIME(6) did start making them appear, we lost the microseconds. Ended up realizing that in local environment we were running MySQLdb 1.2.5 but when deploying to App Engine, even though we had specified "latest" as the version of MySQLdb, it was only pulling 1.2.4b4, hard-coding to 1.2.5 fixed the issue.
Database Functions | Django documentation, Accepts two expressions and returns None if they are equal, otherwise returns expression1 . Caveats Takes an expression representing a DateField , DateTimeField , TimeField , or Add the experiment start year as a field in the QuerySet. DateTimeField – Django Models DateTimeField is a date and time field which stores date, represented in Python by a datetime.datetime instance. As the name suggests, this field is used to store an object of datetime created in python.
Can you please try this solution:
queryset = list(ChangeMetrics.objects.filter(changed__isnull=False, date__isnull=False, version_id__isnull=False))
django.db.models.query | Django documentation, def __iter__(self): queryset = self.queryset query = queryset.query compiler 'DESC' else '') + 'datetimefield') def none(self): """Return an empty QuerySet. Here’s the formal declaration of a QuerySet: class QuerySet(model=None, query=None, using=None, hints=None)¶ Usually when you’ll interact with a QuerySet you’ll use it by chaining filters. To make this work, most QuerySet methods return new querysets. These methods are covered in detail later in this section.
EDIT : Try to move the databse out of your folder, then run
python manage.py syncdb and check if your database is created correctly according to the Models.
Doesn't work : Maybe you can try with this (I don't know if it works, I can't try it now) :
queryset = ChangeMetrics.objects.filter(changed!=None, date!=None, version_id!=None)
Advanced Models - Python Django Tutorials, from events.models import Event >>> import datetime >>> venue1 values() returns Python dictionaries, instead of a QuerySet object: > Returns True if the returned QuerySet contains any objects, False if the QuerySet is empty. There are two Set this to the name of a DateField or DateTimeField to require that this field be unique for the value of the date field. For example, if you have a field title that has unique_for_date="pub_date", then Django wouldn’t allow the entry of two records with the same title and pub_date.
This issue is caused by an outdated version of
MySQL-python not by Django or migrations system.
mysqlclient (which is an updated fork of
MySQL-python) solves this problem.
Filtering for Empty or Null Values in a Django QuerySet, How to Filter for Empty or Null Values in a Django QuerySet import datetime, timedelta >>> Book.objects.filter(date_published__gte=datetime.now() all the matches from the supplied parameters, and returning the QuerySet that remains. * If allow_empty is true, allow_future is false, and the naive result isn't in the future, then return it; otherwise return None. * If allow_empty is false and allow_future is true, return the next date *that contains a valid object*, even if it's in the future. If there are no next objects, return None.
3. API Reference, mongoengine. register_connection (alias, db=None, name=None, host=None, The default queryset, that builds queries and handles a set of results returned from it to convert varying types of date formats into valid python datetime objects. Slicing an unevaluated QuerySet usually returns another unevaluated QuerySet, but Django will execute the database query if you use the “step” parameter of slice syntax, and will return a list. Slicing a QuerySet that has been evaluated (partially or fully) also returns a list.
Django Tips #17 Using QuerySet Latest & Earliest Methods, Similar to the QuerySet methods first and last, the API also offer the earliest and DateTimeField(blank=True, null=True) change_date = models. is that the earliest and latest methods might return instances with null dates. All of these fields are available from the django.contrib.postgres.fields module. Index and Field.db_index both create a B-tree index, which isn’t particularly helpful when querying complex data types. Indexes such as GinIndex and GistIndex are better suited, though the index choice is dependent on the queries that you’re using.
django/query.py at master · django/django · GitHub, router, transaction,. ) from django.db.models import AutoField, DateField, DateTimeField, sql Iterable returned by QuerySet.values() that yields a dict for each row. """ def __init__(self, model=None, query=None, using=None, hints=None):. The DateTimeField (documentation) class in the django.forms module in the Django web framework provides a mechanism for safely handling dates and times as input from HTTP POST requests. The requests are usually generated by an HTML form created from a Django web application. Example 1 from django-filter
- What happens if you just query for the null dates on their own?
- Same result, unfortunately.
- In my case the column was just
datetime, but still this solved the problem. Thanks!
- I ran into this issue with the same local/production environment. Your fix worked like a charm. Didn't know app engine was pulling 1.2.4b4 instead of 1.2.5. Thanks so much @jturmel !
- I get the same results with your query. I can add that the query returns the correct tuples of the DB, i.e. the ones that don't have null in the specified fields. It's only that it doesn't fetch the value of date for some reason.
- Please show your full models.py I mean full
- add above comment in your question please @user3063424
- I added it to the main post.
- There is no such an attribute as
- Tried it. I don't think there is a problem with the query itself... Right now I'm thinking that there is something wrong in the linking between models and database.
- Tried that. And ran a new inspectdb > models.py to generate a fresh models file, still returns None. I'm checking table generations of the db now to see if the error might be there.