peewee DateField property is None with MySQL database
<p>Via <code>pwiz</code> on my MySQL database, I get:</p>

<pre><code>class BaseModel(Model):
    class Meta:
        database = database

class Pub(BaseModel):
    ...
    author = TextField(null=True)
    ...
    publish_date = DateField(null=True)
    ...
</code></pre>

<p>Then, when iterating <code>entry in Pub.select()</code>, <code>entry.publish_date</code> is always <code>None</code>, although all entries in the database have the date set (or at least part of it, such as year, i.e. an entry like <code>2016-00-00</code>).</p>

<p>(There is a <a href="http://stackoverflow.com/questions/12089590/datefield-always-return-none-value">related question</a> but that problem is different: it is not set, and thus the solution was <code>auto_now_add</code>.)</p>

<p>Why is that? Maybe <code>formats</code> is wrong? How to fix this?</p>

<p>How to debug this?</p>

<hr>

<p>Some debugging:</p>

<p>I guess that <code>peewee</code> will use <code>pymsql</code> under the hood. So I tried to do this simple thing:</p>

<pre><code>import pymysql
conn = pymysql.connect(...)
cur = conn.cursor()
cur.execute("SELECT publish_date FROM pub")
</code></pre>

<p>And then iterating <code>row in cur</code>, I will only get <code>row == (None,)</code>.</p>

<p>When casting the value beforehand to <code>char</code>, it works, i.e. I get the value as a string:</p>

<pre><code>cur.execute("SELECT CAST(publish_date AS char) FROM pub")
</code></pre>

<p>I think this is a bug now. I reported this <a href="https://github.com/coleifer/peewee/issues/1086" rel="nofollow">here for peewee</a> and <a href="https://github.com/PyMySQL/PyMySQL/issues/520" rel="nofollow">here for pymysql</a>.</p>

<p>This is a <a href="https://github.com/PyMySQL/PyMySQL/issues/520" rel="nofollow">problem/bug in pymysql</a> although it is not clear yet how pymysql should handle it.</p>

<p>For now, this monkey-patch-method fixes the problem to some degree; it will return the date as a string if it is not representable as a <code>datetime</code> object.</p>

<pre><code>def monkey_patch_pymysql_date_fix():
    import pymysql
    orig_convert_date = pymysql.converters.convert_date
    def fixed_convert_date(obj):
        res = orig_convert_date(obj)
        if res is None:
            return obj
        return res
    pymysql.converters.convert_date = fixed_convert_date
    from pymysql.constants import FIELD_TYPE
    pymysql.converters.decoders[FIELD_TYPE.DATE] = fixed_convert_date
    pymysql.converters.conversions[FIELD_TYPE.DATE] = fixed_convert_date
</code></pre>

python mysql peewee