简体   繁体   中英

Django get weeks from model date to today

I want to get how many weeks it is from a date (that is stored in the .db) from todays date. I tried to work with many answers from the web but can't seem to get it to produce correctly. Most common error I get when trying stuff out is

unsupported operand type(s) for -: 'QuerySet' and 'datetime.date'

The class in models.py

class ADown(models.Model):
    Aname = models.CharField(max_length=200)
    dateStart = models.DateTimeField('date start')
def __unicode__(self):
    return self.Aname

Within views.py - I feel like it's because I'm not really correctly referencing 'dateStart' from the .all()

from django.utils import timezone
from ADown.models import Adown
import datetime

def index(request):

d1 = ADown.objects.all()
totalweeks = (d1 - datetime.date.today()).TotalDays / 7
print totalweeks
latest_poll_list = ADown.objects.order_by('-dateStart')[:5]
template = loader.get_template('ADown/index.html')
context = RequestContext(request, {
    'latest_poll_list': latest_poll_list,
    'totalweek': totalweeks,
    'todays': datetime.now(),
})
return HttpResponse(template.render(context))

And how I call it in .html

</thead>
<tbody>
{% for ADown in latest_poll_list %}
    <tr>
        <td><a>{{ ADown.AName }}</a></td>
        <td><a>{{ totalweek }}</a></td>
        <td><a>{{ ADown.dateStart }}</a></td>
    </tr>
{% empty %}
        <li><a>Something wrong!</a></li>
{% endfor %}
</tbody>
</table>
</div>
{% if latest_poll_list %}

You're taking all ADown objects (queryset object) in your database and substracting the number of weeks of the current month. You must to refer to dateStart in d1 variable to do this.

queryset in this case ADown.objects.all() isn't a valid datetype wich you can operate with a datetime object datetime.date.today() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM