Exemplo n.º 1
0
def addPublisher(request):
    new_publisher = Publisher()
    if request.method == 'POST':
        form = PublisherForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            address = form.cleaned_data['address']
            city = form.cleaned_data['city']
            state_province = form.cleaned_data['state_province']
            country = form.cleaned_data['country']
            website = form.cleaned_data['website']
            phone = form.cleaned_data['phone']

            new_publisher.name = name
            new_publisher.address = address
            new_publisher.city = city
            new_publisher.state_province = state_province
            new_publisher.country = country
            new_publisher.website = website
            new_publisher.phone = phone
            new_publisher.save()

            #return HttpResponse("Publisher Added")
            #return render(request, 'auth_users.html')
            return redirect('/books/home/')
    else:
        form = PublisherForm()
    return render(request, 'publisher.html', {'form': form})
Exemplo n.º 2
0
 def _save_publisher(self):
     print('... Save Model Publisher ...')
     publishers = self.df_books['publisher']
     for p in publishers:
         publisher = Publisher(name=p)
         try:
             publisher.save()
         except IntegrityError:
             pass
Exemplo n.º 3
0
 def handle(self, *args, **options):
   Book.objects.all().delete()
   Publisher.objects.all().delete()
   Author.objects.all().delete()
   print('* Populating books...')
   orderedLS = OrderedDict(lifestudies)
   p = Publisher(name='Living Stream Ministry', code='LSM')
   p.save()
   a = Author(first_name='Witness', last_name='Lee')
   a.save()
   for b, c in orderedLS.items():
     print b
     b = Book(publisher=p, name=b, chapters=c)
     b.save()
     b.author = (a,)
     b.save()
Exemplo n.º 4
0
 def test_models(self):
     data_dicts = set_up_data()
     self.assertTrue(Collection(data_dicts['c']))
     self.assertTrue(Publisher(data_dicts['p']))
     self.assertTrue(Author(data_dicts['a']))
     self.assertTrue(Book(data_dicts['b1']))
     self.assertTrue(Book(data_dicts['b2']))
Exemplo n.º 5
0
def bookDb(request):
    return
    p1 = Publisher(name='Apress',
                   address='2855 Telegraph Avenue',
                   city='Berkeley',
                   state_province='CA',
                   country='U.S.A.',
                   website='http://www.apress.com/')
    p1.save()
    p2 = Publisher(name="O'Reilly",
                   address='10 Fawcett St.',
                   city='Cambridge',
                   state_province='MA',
                   country='U.S.A.',
                   website='http://www.oreilly.com/')
    p2.save()
    return HttpResponse('<p>数据添加成功</p>')
def load_items():
    Publisher.objects.all().delete()
    Book.objects.all().delete()
    StoreChain.objects.all().delete()
    Store.objects.all().delete()

    publishers = [
        Publisher(name=f"Publisher{index}", country=random.choice(countries))
        for index in range(1, PUBLISHERS + 1)
    ]
    Publisher.objects.bulk_create(publishers)

    # create BOOKS_PER_PUBLISHER books for every publishers
    counter = 0
    books = []
    for publisher in Publisher.objects.all():
        for i in range(BOOKS_PER_PUBLISHER):
            counter = counter + 1
            books.append(
                Book(name=f"Book{counter}",
                     price=random.randint(50, 300),
                     issued=datetime.date(year=random.randint(1800, 2010),
                                          month=random.randint(1, 12),
                                          day=random.randint(1, 28)),
                     publisher=publisher))

    Book.objects.bulk_create(books)

    # create STORES stores and insert 100 books in every store
    books = list(Book.objects.all())
    for i in range(STORES):
        temp_books = [
            books.pop(0)
            for i in range(int(PUBLISHERS * BOOKS_PER_PUBLISHER / STORES))
        ]
        store = Store.objects.create(name=f"Store{i + 1}",
                                     marginal_price=random.randint(5, 50))
        store.books.set(temp_books)
        store.save()

    stores = list(Store.objects.all())
    for i in range(CHAINS):
        temp_stores = [stores.pop(0) for i in range(int(STORES / CHAINS - 1))]
        chain = StoreChain.objects.create(name=f"Chain{i+1}",
                                          best_store=random.choice(stores))
        chain.stores.set(temp_stores)
        chain.save()
Exemplo n.º 7
0
def populate_books_database(request):
    from books.models import Publisher
    p1 = Publisher(
        name='Addison-Wesley',
        address='75 Arlington St.',
        city='Boston',
        state_province='MA',
        country='U.S.A.',
        website='http://www.addison-wesley.com/',
    )
    p1.save()

    p2 = Publisher(
        name="O'Reilly",
        address='10 Fawcett St.',
        city='Cambridge',
        state_province='MA',
        country='U.S.A.',
        website='http://www.oreilly.com/',
    )
    p2.save()
    return HttpResponse("Database populated.")
Exemplo n.º 8
0
def dbtest(req):
    ##插入记录
    p1 = Publisher(name='Apress',
                   address='2855 Telegraph Avenue',
                   city='Berkeley',
                   state_province='CA',
                   country='U.S.A.',
                   website='http://www.apress.com/')
    p1.save()  ##插入记录
    print p1.id
    p1.name = 'Apress Publishing'
    p1.save()  ##更新记录

    p2 = Publisher.objects.create(name="O'Reilly",
                                  address='10 Fawcett St.',
                                  city='Cambridge',
                                  state_province='MA',
                                  country='U.S.A.',
                                  website='http://www.oreilly.com/')
    ##查询记录与过滤
    publisher_list = Publisher.objects.all()
    print publisher_list
    publisher_list = Publisher.objects.filter(name='Apress')
    print publisher_list
    publisher_list = Publisher.objects.filter(country="U.S.A.",
                                              state_province="CA")
    Publisher.objects.filter(name__contains="press")
    ##icontains(大小写无关的LIKE),startswith和endswith, 还有range(SQLBETWEEN查询)
    publisher = Publisher.objects.get(
        name="Apress")  ##如果结果是多个对象,会导致抛出异常,没有返回结果也会抛出异常
    Publisher.objects.order_by("name")  ##排序
    Publisher.objects.filter(country="U.S.A.").order_by("-name")
    Publisher.objects.order_by('name')[0]  ##限制数据,等同于limit
    ##更新
    p = Publisher.objects.get(name='Apress')
    p.name = 'Apress Publishing'
    p.save()
    Publisher.objects.filter(id=52).update(name='Apress Publishing')
    Publisher.objects.all().update(country='USA')
    ##删除
    p = Publisher.objects.get(name="O'Reilly")
    p.delete()
    Publisher.objects.filter(country='USA').delete()
    Publisher.objects.all().delete()
Exemplo n.º 9
0
def set_up_data():
    # model1: Collection
    c = Collection(name="Life Studies", code="LS")
    # model2: Publisher
    p = Publisher(name="Living Stream Ministry", code="LSM")
    # model3: Author
    a = Author(first_name="Witness", last_name="Lee", code="WL")
    # make sure all fields allowing blanks are tested
    # model4: Book without author and chapters ascribed
    b1 = Book(isbn=1234567890,
              name="Life Study of Genesis volume 1",
              code="LSG1",
              collection=c,
              publisher=p)
    # model5: Book without collection ascribed
    b2 = Book(isbn=1234567891,
              name="Life Study of Genesis volume 2",
              code="LSG2",
              chapters=25,
              publisher=p)
    return dict([('c', c), ('p', p), ('a', a), ('b1', b1), ('b2', b2)])
Exemplo n.º 10
0
def populate_books_database(request):
	from books.models import Publisher
	p1 = Publisher(
		name='Addison-Wesley',address='75 Arlington St.',
		city='Boston', state_province='MA', country='U.S.A.',
		website='http://www.addison-wesley.com/',
	)
	p1.save()
	
	p2 = Publisher(
		name="O'Reilly", address='10 Fawcett St.',
		city='Cambridge', state_province='MA', country='U.S.A.',
		website='http://www.oreilly.com/',
	)
	p2.save()
	return HttpResponse("Database populated.")
Exemplo n.º 11
0
def dbtest(req):
    ##插入记录
    p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
                   city='Berkeley', state_province='CA', country='U.S.A.',
                   website='http://www.apress.com/')
    p1.save()  ##插入记录
    print p1.id
    p1.name = 'Apress Publishing'
    p1.save()  ##更新记录

    p2 = Publisher.objects.create(name="O'Reilly",
                                  address='10 Fawcett St.', city='Cambridge',
                                  state_province='MA', country='U.S.A.',
                                  website='http://www.oreilly.com/')
    ##查询记录与过滤
    publisher_list = Publisher.objects.all()
    print publisher_list
    publisher_list = Publisher.objects.filter(name='Apress')
    print publisher_list
    publisher_list = Publisher.objects.filter(country="U.S.A.", state_province="CA")
    Publisher.objects.filter(name__contains="press")
    ##icontains(大小写无关的LIKE),startswith和endswith, 还有range(SQLBETWEEN查询)
    publisher = Publisher.objects.get(name="Apress")  ##如果结果是多个对象,会导致抛出异常,没有返回结果也会抛出异常
    Publisher.objects.order_by("name")  ##排序
    Publisher.objects.filter(country="U.S.A.").order_by("-name")
    Publisher.objects.order_by('name')[0]  ##限制数据,等同于limit
    ##更新
    p = Publisher.objects.get(name='Apress')
    p.name = 'Apress Publishing'
    p.save()
    Publisher.objects.filter(id=52).update(name='Apress Publishing')
    Publisher.objects.all().update(country='USA')
    ##删除
    p = Publisher.objects.get(name="O'Reilly")
    p.delete()
    Publisher.objects.filter(country='USA').delete()
    Publisher.objects.all().delete()
Exemplo n.º 12
0
#coding=utf-8
#测试插入数据
from books.models import Publisher

p1 = Publisher(name='Apress',address='2855 Telegraph Avenu',
	city='Berkeley',state_province='CA',country='U.S.A',
	website='http;//www.apress.com')

p1.save()

publisher_list = Publisher.objects.all()
publisher_list

print publisher_list
Exemplo n.º 13
0
__author__ = 'leo'

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

from books.models import Publisher

p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
               city='Berkeley', state_province='CA', country='U.S.A.',
               website='http://www.apress.com/')
p1.save()

p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',
               city='Cambridge', state_province='MA', country='U.S.A.',
               website='http://www.oreilly.com/')
p2.save()







publisher_list = Publisher.objects.all()
Exemplo n.º 14
0
        full_content = models.TextField('全部内容') # text 类型
        authors = models.ManyToManyField(Author) # 对应一个或多个authors(many-to-many);会创建关联表来维护
        publisher = models.ForeignKey(Publisher) # 对应一个单独的publisher(one-to-many);会创建外键来维护
        # 以下是一一对应关系的写法, 第一个参数是关联的对象,  verbose_name 是说明
        # place = models.OneToOneField(Place, verbose_name="related place")


2.model操作
    # 执行命令
    python manage.py shell  # 先进入django的shell, 以加载设置后再运行

    ####################### 执行python ######################
    from books.models import Publisher,Book # import模型类

    # 新增、保存
    p = Publisher(name='Apress', address='2560 Ninth St.', website='http://www.apress.com/') # 创建模型类对象,并赋值
    print( p._state.adding ) # 打印:True 。实例的“._state.adding”属性当此实例还没有保存到数据库前都是 True, 由数据库查询出来的是 False。 用来判断对象是否需要 insert
    p.save() # 将一个对象保存到数据库, 后台Django在这里执行了一条 INSERT SQL语句
    p = Publisher(name="O'Reilly", address='10', website='http://www.oreilly.com/')
    p.save(force_insert=True) # save 函数加上 force_insert=True 时会强制执行 insert,新增时减少一次 update(不加则会先试试update再insert)
    Joe = Publisher.objects.create(name="Joe", address='10 N') # 直接保存到数据库, 并返回这个对象
    print( Joe._state.adding ) # 打印:False 。实例的“._state.adding”当数据已经存到数据库都返回 False
    book = Book.objects.get(title="ddkk")
    book.publisher.add(Joe) # 添加关联类(调用它的 add 函数)
    obj, result = Publisher.objects.get_or_create(name='Apress', address='Ninth St.', website='http://www.xx.com/')
    # get_or_create 有则返回查询结果(返回: 结果类, False), 没有则新增一个(返回: 新增后的结果类,True)

    # 更新
    publisher = Publisher.objects.get(id=1) # 这只获取到一个对象
    publisher.name = 'test_name'
    publisher.save() # 执行更新语句(会更新除了主键之外的所有字段)
Exemplo n.º 15
0
 def test_create_publisher_with_exists_name_raises_error(self):
     publisher = PublisherFactory()
     new_publisher = Publisher(name=publisher.name)
     with self.assertRaises(IntegrityError):
         new_publisher.save()
Exemplo n.º 16
0
# ========================= Database objects ========================
# ___________________________________________________________________________

# begins half way down page:
# http://www.djangobook.com/en/1.0/chapter05/



>>> from books.models import Publisher

# listing data
>>> Publisher.objects.all()

# create new instances
p = Publisher(name='Apress',address='2855 Telegraph Ave.', city='Berkeley', state_province='CA', country='U.S.A.', website='http://www.apress.com/')
p.save()

# filtering data
>>>> Publisher.objects.filter(name="Apress")
>>>> Publisher.objects.filter(name__contains="press")
#>>>> Poll.objects.filter(question__startswith='What')

# returning single object using .get
>>> Publisher.objects.get(name="Apress Publishing")
>>>> Publisher.objects.get(country="U.S.A.")

# ordering data
>>> Publisher.objects.order_by("name")
>>> Publisher.objects.order_by("address")
Exemplo n.º 17
0
# run this command at the terminal prompt
# python manage.py shell

# within the shell, run the following commands

# (1) Add two books

from books.models import Publisher

p1 = Publisher(name='Apress', address='2855 Telegraph Avenue', city='Berkeley',
               state_province = 'CA', country='U.S.A', website='http://www.apress.com')
p1.save()

# Roughly Translated to SQL =>
#
#   INSERT INTO books_publisher
#       (name, address, city, state_province, country, website)
#   VALUES
#       ('Apress', '2855 Telegraph Avenue', 'Berkeley', 'CA',
#        'U.S.A.','http://www.apress.com')
#

p2 = Publisher(name="O'Reilly", address='10 Fawcett St.', city='Cambridge',
               state_province = 'MA', country='U.S.A', website='http://www.oreilly.com')
p2.save()


# (2) Show the list of books

publisher_list = Publisher.objects.all()
Exemplo n.º 18
0
# -*- coding:utf-8 -*-
#测试模型的
from books.models import Publisher

if __name__ == '__main__':
    p1 = Publisher(name='Apress',
                   address="2855 Telegraph Ave",
                   city="Berkeley",
                   state_province="CA",
                   country="USA",
                   website='http://www.apress.com/')
    p1.save()
    
    p2=Publisher.objects.create(name="O'Reilly",
                                address='10 Fawcett St.',
                                city="Cambridge",
                                state_province="MA",
                                country="USA",
                                website="http://www.oreilly.com")
    publisher_list=Publisher.objects.all()
    print publisher_list
    p1.name='Apress Publishing'
    p1.save()
    print p1.name
    publisher_list=Publisher.objects.filter(country="USA").order_by("-name")
    print publisher_list
    print Publisher.objects.order_by('name')[0]
    print Publisher.objects.all().count()
    print Publisher.objects.all().delete()
    print Publisher.objects.all()
    
Exemplo n.º 19
0
def crudops(request):
    #Creating an entry

    publisher = Publisher(name='Apress',
                          address='2855 Telegraph Avenue',
                          city='Berkeley',
                          state_province='CA',
                          country='U.S.A.',
                          website='http://www.apress.com/')
    publisher.save()

    #Read ALL entries
    objects = Publisher.objects.all()
    res = 'Printing all Publisher entries in the DB : <br>'

    for elt in objects:
        res += elt.name + "<br>"

    # #Read a specific entry:
    # sorex = Publisher.objects.get(name = "Apress1")
    # res += 'Printing One entry <br>'
    # res += sorex.name

    #Delete an entry
    #res += '<br> Deleting an entry <br>'

# sorex.delete()

#Update
    publisher = Publisher(name='Apress1',
                          address='2855 Telegraph Avenue',
                          city='Berkeley',
                          state_province='CA',
                          country='U.S.A.',
                          website='http://www.apress.com/')

    publisher.save()
    res += 'Updating entry<br>'

    publisher = Publisher.objects.get(name='Apress1')
    publisher.name = 'thierry'
    publisher.save()
    Publisher.objects.filter(id=27).update(name='Apress Publishing')
    Publisher.objects.all().update(country='USA')

    return HttpResponse(res)
Exemplo n.º 20
0
from books.models import Publisher
p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',city='Berkeley', state_province='CA', country='U.S.A.',website='http://www.apress.com/')
p1.save()
p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',city='Cambridge', state_province='MA', country='U.S.A.',website='http://www.oreilly.com/')
p2.save()
p3 = Publisher(name="O'Reilly",)
p3.save()
p4 = Publisher.objects.create(name='learning django',)
publisher_list = Publisher.objects.all()
publisher_list