On Fri, 2009-04-03 at 13:14 -0700, Albert wrote:
> 
> class Musician(models.Model):
>     first_name = models.CharField(max_length=50)
>     last_name = models.CharField(max_length=50)
> 
> class Album(models.Model):
>     artist = models.ForeignKey(Musician)
>     name = models.CharField(max_length=100)
> 
> 
> Now in `Musician` I want to add a field "last_album".
> How can I do that? I'd like to be able to write:
> 
> m = Musician(pk=1)
> print m.last_album.name

I suggest you this solution:

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    albums = models.ManyToManyField("Album")
    
    def last_album(self):
        return self.albums.order_by("pub_date")[-1]

class Album(models.Model):
    artist = models.ForeignKey(Musician)
    name = models.CharField(max_length=100)
    pub_date = models.DateField()

-- 
Marco Buttu




--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to