django数据无法导入到数据库,是我代码的问题忙?
我是django的新手,我想请教以一下
我使用模型层创建了模型,里面有字段
class Rating(models.Model): user_id = models.CharField(max_length=16)
movie_id = models.CharField(max_length=16)
rating = models.DecimalField(decimal_places=2, max_digits=4)
rating_timestamp = models.DateTimeField()
type = models.CharField(max_length=8, default='explicit')
def __str__(self):
return "user_id: {}, movie_id: {}, rating: {}, type: {}"\
.format(self.user_id, self.movie_id, self.rating, self.type)
class Cluster(models.Model):
cluster_id = models.IntegerField()
user_id = models.IntegerField()
def __str__(self):
return "{} in {}".format(self.user_id, self.cluster_id)
使用python xxx.py执行这段语句
import osimport urllib.request
import django
import datetime
import decimal
from tqdm import tqdm
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()
from analytics.models import Rating
def create_rating(user_id, content_id, rating, timestamp):
rating = Rating(user_id=user_id, movie_id=content_id, rating=decimal.Decimal(rating),
rating_timestamp=datetime.datetime.fromtimestamp(float(timestamp)))
rating.save()
return rating
def download_ratings(): URL = 'https://gitee.com/zhangyoushang/wokkk/blob/master/latest/ratings.dat'
response = urllib.request.urlopen(URL)
data = response.read()
print('download finished')
return data.decode('utf-8')
def delete_db():
print('truncate db')
Rating.objects.all().delete()
print('finished truncate db')
def populate():
delete_db()
ratings = download_ratings()
for rating in tqdm(ratings.split(sep="\n")):
r = rating.split(sep="::")
if len(r) == 4:
create_rating(r[0], r[1], r[2], r[3])
if __name__ == '__main__':
print("Starting MovieGeeks Population script...")
populate()
但是我发现我的数据库是空,里面没有数据。
也没有报错,执行如下:
怎么弄也弄不好,求大神指点!
回答:
应该是数据下载失败了,你检查下 download_ratings
的输出,可能是没有授权或 Gitee 另外做了限制,下载的并不是你要的文件,而是一个 HTML 文本,建议手动直接下好放到本地。
以上是 django数据无法导入到数据库,是我代码的问题忙? 的全部内容, 来源链接: utcz.com/p/938223.html