在main函数中使用django模型(附django正反向的外键关联查询)

aweilark 2020-03-06

用一个django外键关联的正反向查询做例子

import os

if __name__ == '__main__':
    #加载Django项目的配置信息
    os.environ.setdefault("DJANGO_SETTINGS_MODULE","dispy.settings.stg")
    #导入Django,并启动Django项目
    import django
    django.setup()

    from ormtest import models

    #正向查询(查找书的类型对象,然后通过外键关联,在出版社列中查出那家出版社)
    book_obj = models.Book.objects.first()
    book_obj_publisher = book_obj.publisher.name
    print("书名:",book_obj,"出版社为:",book_obj_publisher)

    #反向查询
    publisher_obj = models.Publisher.objects.first()
    print(publisher_obj)
    publisher_obj_book = publisher_obj.books.all()      
    #books为book类中定义的related_name
    print(publisher_obj_book)

相关推荐

inspuryhq / 0评论 2020-07-28