• 086~088:QuerySet API详解-get、create、get_or_create和bulk_create方法


    QuerySet API详解-get、create、get_or_create和bulk_create方法:

    create :创建一条数据,并且保存到数据库中。这个方法相当于先用指定的模型创建一个对象,然后再调用这个对象的 save 方法。示例代码如下:

    article = Article(title='abc')
    article.save()
    # 下面这行代码相当于以上两行代码
    article = Article.objects.create(title='abc')

    get_or_create :根据某个条件进行查找,如果找到了那么就返回这条数据,如果没有查找到,那么就创建一个。示例代码如下:

    obj,created= Category.objects.get_or_create(title='默认分类')

    如果有标题等于 默认分类 的分类,那么就会查找出来,如果没有,则会创建并且存储到数据库中。
    这个方法的返回值是一个元组,元组的第一个参数 obj 是这个对象,第二个参数 created 代表是否创建的。

    数据库模型中也可以怎么搞:

    def publisher_default():
        return Publisher.objects.get_or_create(name="默认出版社")
    
    class Book(models.Model):
        name = models.CharField(max_length=300)
        pages = models.IntegerField()
        price = models.FloatField()
        rating = models.FloatField()
        author = models.ForeignKey(Author,on_delete=models.CASCADE)
        publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)
        # publisher = models.ForeignKey(Publisher, on_delete=models.SET_DEFAULT, default=publisher_default)

    bulk_create :一次性创建多个数据。示例代码如下:

    Tag.objects.bulk_create([Tag(name='111'), Tag(name='222')])

    实例代码和截图:

        # book = Book.objects.get(pk=1)
        # print(book)
    
        # publisher = Publisher.objects.create(name="工业出版社")
        # print(publisher)
    
        # publisher = Publisher.objects.get_or_create(name="电子出版社")
        # print(publisher)
    
        publisher = Publisher.objects.bulk_create([Publisher(name="123"), Publisher(name="xyz")    ])

  • 相关阅读:
    CentOS 7修改用户密码
    Java EE(Web)大方向
    【Spring学习随笔】4. Spring AOP
    Git从本地上传项目到Github
    Vue及Vue-Cli的环境搭建(Windows)
    【Spring学习随笔】3. Spring Bean
    SSM框架随笔
    IDEA中Spring配置错误:class path resource [.xml] cannot be opened because it does not exist
    Jsp技术
    【Spring学习随笔】2. Spring IoC
  • 原文地址:https://www.cnblogs.com/zheng-weimin/p/10284600.html
Copyright © 2020-2023  润新知