Tuesday, 5 March 2019

django 11



#music/models

from django.db import models

class Album(models.Model):
    artist = models.CharField(max_length=50)
    album_title = models.CharField(max_length=50)
    genre = models.CharField(max_length=50)
    album_logo = models.CharField(max_length=500)

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

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=50)
    song_title = models.CharField(max_length=50)

    def __str__(self):
        return self.song_title

--------------------------------
#python shell

>>> from music.models import Album, Song
>>> album1 = Album.objects.get(pk=1)
>>> album1
<Album: Red - Taylor Swift>
>>> song = Song()
>>> song.album = album1
>>> song.file_type = 'mp3'
>>> song.song_title = 'I hate my boyfriend'
>>> song
<Song: I hate my boyfriend>
>>> song.file_type
'mp3'
>>> song.save()
>>> song.song_title = 'I love my boyfriend'
>>> song.save()

------------------------------------------
#python shell

>>> from music.models import Album, Song
>>> album1 = Album.objects.get(pk=1)
>>> album1.song_set.all()
<QuerySet [<Song: I love my boyfriend>]>
>>> album1.song_set.create(song_title='I love bacon', file_type='avi')
<Song: I love bacon>
>>> song = album1.song_set.create(song_title='I love bacon', file_type='avi')
>>> song.song_title
'I love bacon'
>>> song.album
<Album: Red - Taylor Swift>
>>> album1.song_set.count()
3

------------------------------------
#music/templates/music/details

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Detail</title>
</head>
<body>
    <img src="{{album.album_logo}}">
    <h1>{{album.album_title}}</h1>
    <h3>{{album.artist}}</h3>

    <ul>
        {% for song in album.song_set.all %}
            <li>{{song.song_title}} - {{song.file_type}}</li>
        {% endfor %}
    </ul>
</body>
</html>

No comments:

Post a Comment