コード例 #1
0
ファイル: views.py プロジェクト: gaoqiangzy/python-dialog
def index(request):
    '''
    操作rom
    1.所有的模型类都有个objects属性,就是一个manager对象,用于进行数据操作管理
    2.添加数据
        2.1 模型类。objects.create(属性=值)
                返回生成的对象----》记录
        2.2 添加数据
            对象 = 模型类()
            对象。属性=值
            对象。save()保存数据
        2.3 ,模型类。objects.get_or_crate(属性=值)
            如果有就获取,没有就创造
    3查看数据
            模型类。objects.all() 查看所有数据
            模型类。objects.filter(条件)条件查询,相当于where
            模型类。objects.get(条件)只能获取一条数据
    4修改数据
            4.1 模型类。object。filter(条件).update(属性=新属性值)
                一次更新多条
            4.2 先查询出对象  ---一次更新一条
                对象。属性=值
                对象。属性=值
                对象。属性=值
                对象。save()
        5 删除数据
            查询偶delete()
    :param request:
    :return:
    '''
    rs = Book.objects.create(name='红楼梦', author='曹雪芹', price=9.9)
    print(rs)
    book = Book()
    book.name = '红楼梦'
    book.author = '曹雪芹'
    book.price = 99
    book.save()
    book = Book.objects.get_or_create(name='三国演义', author='施耐庵', price=88)
    print(book)

    #查看数据
    # books=Book.objects.all()
    # content = {
    #     "books":books
    # }
    # book = Book.objects.get(id=1)
    # book = Book.objects.get(name='红楼梦')  如果存在多条数据,返回列表[]
    # books = Book.objects.filter(name='红楼梦').first()#获取第一条
    # print(book)

    #更新数据
    # rs = Book.objects.filter(name='红楼梦').update(name='红楼2')
    # print(rs)
    # book = Book.objects.get(id=1)
    # book.name='红楼3'
    # book.save()
    book = Book.objects.get(id=1)
    book.delete()
    return HttpResponse("bookModel")
コード例 #2
0
ファイル: generic.py プロジェクト: ch3ka/codingcontest2012
def do_import(data, if_book_exists='continue'):
    """import a book in the database. 
    
    Expects a dict of the following format:
{ 'publisher': (u'oreilly', u"Farnham ; O'Reilly, 2002 printing, c2003."), 'authors': [(u'ray_randy_j', u'Ray, Randy J.'), (u'kulchenko_pavel', u'Kulchenko, Pavel')], 'subjects': [(u'perl_computer_program_language', u'Perl (Computer program language)'), (u'internet_programming', u'Internet programming')], 'language': u'eng', 'title': u'Programming Web services with Perl', 'ddc': u'5.2762', 'long_title': None, 'edition_info': u'', 'summary': None }
    which other importers have to deliver.

    if_book_exists may be eighter one of 'continue', 'overwrite', 'error'
    """

    try:
        book = Book.objects.get(isbn=data['isbn'])
    except Book.DoesNotExist:
        book = Book(isbn=data['isbn'], title=data['title'], 
                    long_title=data.get('long_title'), language=data.get('language'), 
                    ddc=data.get('ddc'), edition_info=data.get('edition_info'), 
                    summary=data.get('summary'))  
        try:
            publisher = Publisher.objects.get(publisher_id=data['publisher'][0])
        except Publisher.DoesNotExist:
            publisher = Publisher(publisher_id=data['publisher'][0], name=data['publisher'][1])
            publisher.save()
        book.publisher = publisher

        for authordata in data['authors']:
            try:
                author = Author.objects.get(author_id=authordata[0])
            except Author.DoesNotExist:
                author = Author(author_id=authordata[0], name=authordata[1])
                author.save()
            book.authors.add(author)

        for subjectdata in data['subjects']:
            try:
                subject = Subject.objects.get(subject_id=subjectdata[0])
            except Subject.DoesNotExist:
                subject = Subject(subject_id=subjectdata[0], name=subjectdata[1])
                subject.save()
            book.subjects.add(subject)

        book.save()
    else:
        if if_book_exists.lower() == "error":
            raise ValueError("Book %s already exists!" % data['isbn'])
        elif if_book_exists.lower() == "overwrite":
            book.delete()
            do_import(data)
        elif if_book_exists.lower() != "continue":
            raise ValueError("if_book_exists must be eighter one of 'continue', 'overwrite', 'error'")
コード例 #3
0
def edit_book_save(request):
    action = request.POST.get("action")
    book_id = request.POST.get("book_id")
    subject = request.POST.get("subject")
    summary = request.POST.get("content")
    open_yn = request.POST.get("open_yn")
    ccl_left = request.POST.get("ccl_left")
    ccl_right = request.POST.get("ccl_right")
    adv_yn = request.POST.get("adv_yn")
    adv_content = request.POST.get("adv_content")
    adv_mobile_content = request.POST.get("adv_mobile_content")

    book = Book.objects.get(id=book_id)

    if request.user not in book.user.all():
        request.session["error_message"] = u"수정권한이 없습니다"
        return redirect('/book/%s' % book.id)

    if action == "modify":
        form = BookEditForm(request.POST)
        if not form.is_valid():
            request.session["error"] = form
        else:
            reversion_comments = []
            if book.subject != subject: reversion_comments.append(u"제목")
            if book.summary != summary: reversion_comments.append(u"책요약")
            if book.open_yn != open_yn: reversion_comments.append(u"공개여부")
            if book.ccl_left != ccl_left or book.ccl_right != ccl_right:
                reversion_comments.append(u"저작권")

            book.subject = subject
            book.summary = summary
            book.open_yn = open_yn
            book.ccl_left = ccl_left
            book.ccl_right = ccl_right
            book.adv_yn = adv_yn
            book.adv_content = adv_content
            book.adv_mobile_content = adv_mobile_content
            book.modify_time = datetime.datetime.now()

            if 'image' in request.FILES:
                file_content = ContentFile(request.FILES['image'].read())
                book.image.save(request.FILES['image'].name, file_content)
                reversion_comments.append(u"이미지")
                resize_image(book.image.path, width=100, height=130)

            if reversion_comments:
                reversion.set_comment(u"%s (이)가 변경되었습니다." %
                                      u", ".join(reversion_comments))

            book.save()
            request.session["edit_message"] = u"책이 수정되었습니다"

    elif action == "add":
        book = Book(subject=subject,
                    summary=summary,
                    open_yn=open_yn,
                    ccl_left=ccl_left,
                    ccl_right=ccl_right,
                    creator=request.user)
        book.save()
        book.user.add(request.user)

        page = Page(book=book, subject="FrontPage")
        page.save()

        if 'image' in request.FILES:
            file_content = ContentFile(request.FILES['image'].read())
            book.image.save(request.FILES['image'].name, file_content)

        request.session["edit_message"] = u"책이 추가되었습니다"

    elif action == "delete":
        book.delete()
        # request.session["edit_book_message"] = u"책이 삭제되었습니다"

    # rearrange_page(page.book)
    cache_clear(book)

    if action == "delete":
        return redirect("/")
    else:
        return redirect("/edit/book/%s" % book.id)
コード例 #4
0
ファイル: views.py プロジェクト: pahkey/wikidocs
def edit_book_save(request):
    action = request.POST.get("action")
    book_id = request.POST.get("book_id")
    subject = request.POST.get("subject")
    summary = request.POST.get("content")
    open_yn = request.POST.get("open_yn")
    ccl_left = request.POST.get("ccl_left")
    ccl_right = request.POST.get("ccl_right")
    adv_yn = request.POST.get("adv_yn")
    adv_content = request.POST.get("adv_content")
    adv_mobile_content = request.POST.get("adv_mobile_content")

    book = Book.objects.get(id=book_id)

    if request.user not in book.user.all() and not request.user.is_superuser:
        request.session["error_message"] = u"수정권한이 없습니다"
        return redirect('/book/%s' % book.id)

    if action == "modify":
        form = BookEditForm(request.POST)
        if not form.is_valid():
            request.session["error"] = form
        else:
            reversion_comments = []
            if book.subject != subject: reversion_comments.append(u"제목")
            if book.summary != summary: reversion_comments.append(u"책요약")
            if book.open_yn != open_yn: reversion_comments.append(u"공개여부")
            if book.ccl_left != ccl_left or book.ccl_right != ccl_right: reversion_comments.append(u"저작권")

            book.subject = subject
            book.summary = summary
            book.open_yn = open_yn
            book.ccl_left = ccl_left
            book.ccl_right = ccl_right
            book.adv_yn = adv_yn
            book.adv_content = adv_content
            book.adv_mobile_content = adv_mobile_content
            book.modify_time = datetime.datetime.now()

            if 'image' in request.FILES:
                file_content = ContentFile(request.FILES['image'].read())
                book.image.save(request.FILES['image'].name, file_content)
                reversion_comments.append(u"이미지")
                resize_image(book.image.path, width=100, height=130)

            if reversion_comments:
                reversion.set_comment(u"%s (이)가 변경되었습니다." % u", ".join(reversion_comments))

            book.save()
            request.session["edit_message"] = u"책이 수정되었습니다"

    elif action == "add":
        book = Book(subject=subject, summary=summary, open_yn=open_yn, ccl_left=ccl_left, ccl_right=ccl_right, creator=request.user)
        book.save()
        book.user.add(request.user)

        page = Page(book=book, subject="FrontPage")
        page.save()

        if 'image' in request.FILES:
            file_content = ContentFile(request.FILES['image'].read())
            book.image.save(request.FILES['image'].name, file_content)

        request.session["edit_message"] = u"책이 추가되었습니다"

    elif action == "delete":
        book.delete()
        # request.session["edit_book_message"] = u"책이 삭제되었습니다"

    # rearrange_page(page.book)
    cache_clear(book)

    if action == "delete":
        return redirect("/")
    else:
        return redirect("/edit/book/%s" % book.id)