PerryDaPlatypus PerryDaPlatypus - 3 months ago 13
MySQL Question

Convert MySQL Query to Django query

I'm converting a FlaskApp to Django. In my Flask App I was doing straight DB queries w/o an ORM like MySQLAlchemy.

I'm having trouble converting my count queries for use in Django. Seems simple enought, but I'm missing something.

OLD FUNCTION W/ QUERY

def countClients(db, begin, end, type):
c = db.cursor()
query = "SELECT COUNT(*) FROM newclients WHERE method LIKE %s AND (enddate BETWEEN %s AND %s)"
c.execute(query, (type, begin, end))
output = int(c.fetchone()[0])
return output


NEW QUERY

for year in range(2015, today.year):
for month in range(1, 13):
startdate = datetime.date(year, month, 1)
enddate = last_day_of_month(startdate)
try:
Count14.append(
newclients.objects.filter(method = 'Test Drive',
enddate__range=(startdate, enddate)
)
).count()


WHAT I'VE TRIED


  • Query without Try:Except



w/o the try except I get a traceback

'NoneType' object has no attribute 'count'



  • Adding a int() around the query



But the int function can't accept a queryset.

NOTE
I have used portions of these queries successfully, but these what I'm trying here is more complex than the others.

i.e. This one works, but is simpler.

clients = newclients.objects.filter(method=method_query).filter(enddate__range=(begindate, enddate))

Answer

Your .count() is in the wrong place. It needs to be after the second close parenthesis, not the third.

As it is, you are calling it on the result of append, which is always None.