python django 获取数据 下载文件
获取数据:
- 使用Django ORM获取数据
Django ORM是Django中的一个重要组件,它提供了一个高级的接口来操作数据库。通过Django ORM,我们可以很方便地获取数据库中的数据。
示例代码:
from myapp.models import MyModel
# 获取所有数据
all_data = MyModel.objects.all()
# 获取符合条件的数据
filter_data = MyModel.objects.filter(name='test')
# 获取第一条数据
first_data = MyModel.objects.first()
# 获取最后一条数据
last_data = MyModel.objects.last()
# 获取数据数量
data_count = MyModel.objects.count()
- 使用原生SQL查询获取数据
除了Django ORM,我们还可以使用原生SQL语句来查询数据库中的数据。
示例代码:
from django.db import connection
# 查询所有数据
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM myapp_mymodel")
all_data = cursor.fetchall()
# 查询符合条件的数据
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM myapp_mymodel WHERE name=%s", ['test'])
filter_data = cursor.fetchall()
下载文件:
- 使用Python内置模块urllib.request下载文件
示例代码:
import urllib.request
url = 'http://example.com/file.zip'
local_file = 'file.zip'
urllib.request.urlretrieve(url, local_file)
- 使用第三方库requests下载文件
示例代码:
import requests
url = 'http://example.com/file.zip'
local_file = 'file.zip'
response = requests.get(url)
with open(local_file, 'wb') as f:
f.write(response.content)
``
原文地址: https://www.cveoy.top/t/topic/fI2t 著作权归作者所有。请勿转载和采集!