一个属性是更新,另一个则不是

时间:2016-03-23 14:29:17

标签: python django

我正在阅读tutorial,并试图实施锻炼。练习是:

  

更新您的填充脚本,以便Python类别有128个视图和64个喜欢,Django类别有64个视图和32个喜欢,而其他框架类别有32个视图和16个喜欢。

所以,我在人口脚本中做了同样的事情:

def add_cat(name,likes,views):
c = Category.objects.get_or_create(name=name)[0]
c.likes = likes
print c.likes
c.views = views
return c

整个脚本是:

  import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')

import django
django.setup()

from rango.models import Category, Page


def populate():
    python_cat = add_cat('Python',64,128)

    add_page(cat=python_cat,
        title="Official Python Tutorial",
        url="http://docs.python.org/2/tutorial/")

    add_page(cat=python_cat,
        title="How to Think like a Computer Scientist",
        url="http://www.greenteapress.com/thinkpython/")

    add_page(cat=python_cat,
        title="Learn Python in 10 Minutes",
        url="http://www.korokithakis.net/tutorials/python/")

    django_cat = add_cat("Django",32,64)

    add_page(cat=django_cat,
        title="Official Django Tutorial",
        url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/")

    add_page(cat=django_cat,
        title="Django Rocks",
        url="http://www.djangorocks.com/")

    add_page(cat=django_cat,
        title="How to Tango with Django",
        url="http://www.tangowithdjango.com/")

    frame_cat = add_cat("Other Frameworks",16,32)

    add_page(cat=frame_cat,
        title="Bottle",
        url="http://bottlepy.org/docs/dev/")

    add_page(cat=frame_cat,
        title="Flask",
        url="http://flask.pocoo.org")

    # Print out what we have added to the user.
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print "- {0} - {1}".format(str(c), str(p))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title)[0]
    p.url=url
    p.views=views
    p.save()
    return p

def add_cat(name,likes,views):
c = Category.objects.get_or_create(name=name)[0]
c.likes = likes
print c.likes
c.views = views
return c

# Start execution here!
if __name__ == '__main__':
    print "Starting Rango population script..."
    populate()

现在,我想打印喜欢和喜欢的价值观。观点:

>>> c = Category.objects.get(pk = 3)
>>> c
<Category: Python>
>>> c.likes
0
>>> c.views
128
>>> 

当视图得到更新时,喜欢的值不会改变。

1 个答案:

答案 0 :(得分:0)

您需要保存对象,有关详细信息,请查看this

def add_cat(name,likes,views):
    c = Category.objects.get_or_create(name=name)[0]
    c.likes = likes
    print c.likes
    c.views = views
    c.save()
    return c