add_albums.py 文件源码

python
阅读 24 收藏 0 点赞 0 评论 0

项目:decouvrez_django 作者: oc-courses 项目源码 文件源码
def handle(self, *args, **options):
        reference = 0
        # open file with data
        directory = os.path.dirname(os.path.dirname(__file__))
        path = os.path.join(directory, 'data', 'albums.yml')
        with open(path, 'r') as file:
            data = yaml.load(file)
            albums = data['albums']
            for album in albums:
                # Create artists
                artists = []
                for artist in album['artists']:
                    try:
                        stored_artist = Artist.objects.get(name=artist)
                        lg.info('Artist found: %s'%stored_artist)
                    except ObjectDoesNotExist:
                        stored_artist = Artist.objects.create(name=artist)
                        lg.info('Artist created: %s'%stored_artist)
                    artists.append(stored_artist)
                # Find or create album
                try:
                    stored_album = Album.objects.get(title=album['title'])
                    lg.info('Album found: %s'%stored_album.title)
                except ObjectDoesNotExist:
                    reference += 1
                    album = Album.objects.create(
                        title=album['title'],
                        reference=reference,
                        picture=album['picture']
                    )
                    album.artists = artists
                    lg.info('New album: %s'%stored_artist)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号