【问题标题】:CSV to Django Model to Display AdminCSV 到 Django 模型以显示管理员
【发布时间】:2018-08-14 18:40:20
【问题描述】:

我已经搜索并尝试了所有方法,但无法让我的 csv 文件填充并显示在 Django Admin 中。 请注意以下所有文件都在同一目录中,包括 csv。

这是我的models.py

from django.db import models


class Album(models.Model):
    artist = models.CharField(max_length=100)
    album_title = models.CharField(max_length=100)
    genre = models.CharField(max_length=100)
    album_logo = models.CharField(max_length=1000)

    def __str__(self):
        return self.album_title + ' - ' + self.artist

    class Meta:
        verbose_name_plural = 'Album'

这是我的 import.py 文件:

import csv
from music.models import Album

with open('names.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        artist = row['artist']
        album_title = row['album_title']
        genre = row['genre']
        album_logo = row['album_logo']

        new_album = Album(artist=artist, album_title=album_title, genre=genre, album_logo=album_logo)
        new_album.save()

我运行服务器并且管理员拥有表和数据库,但它没有填充我的 csv 文件数据。任何帮助,将不胜感激。谢谢。

【问题讨论】:

    标签: python django csv django-models import-csv


    【解决方案1】:

    问题是你的import.py 永远不会被执行。我假设这只是一次?它不应该在每次你的 Django 服务器统计时都执行。

    要执行您的代码,您可以在 shell 中执行(请参阅this answer):

    manage.py shell < import.py
    

    或者使用custom management command

    【讨论】:

      猜你喜欢
      • 2014-09-08
      • 2014-12-01
      • 2019-09-22
      • 2021-09-14
      • 1970-01-01
      • 2021-12-11
      • 2023-03-14
      • 2017-05-08
      • 2010-12-03
      相关资源
      最近更新 更多