1

Following up with the posting regarding reversed many-to-many look ups, I was wondering what the best practice for my project/picture problem is:

I want to register a number of projects and the users can upload (but not required) multiple project pictures.

Therefore I defined the following two classes:

from easy_thumbnails.fields import ThumbnailerImageField

class Project(models.Model):
    name = models.CharField(_('Title'), max_length=100,)
    user = models.ForeignKey(User, verbose_name=_('user'),)
    ...

class ProjectPicture(models.Model):
    project = models.ForeignKey('Project')
    picture = ThumbnailerImageField(_('Image'),
            upload_to='user/project_pictures/', null=True, blank=True,)

    def __unicode__(self):
        return u'%s\'s pictures' % (self.project.name)

So for every user, I am displaying their projects in a "dashboard" via

projects = Project.objects.filter(user = logged_user)

which returns a list of projects with the names, etc.

Now I would like to display a picture of the project in the dashboard table. Therefore I have two questions I am seeking advice for:

1) Is the class setup actually the best way to do it? I split up the classes like shown above to allow the users to upload more than one picture per project. Would there be a better way of doing it?

2) How can I display the first picture of a project in the template, if a picture is available? Do I need to make a query on every ProjectPicture object which corresponds to a Project? Or is there an elegant Django solution for that problem?

Community
  • 1
  • 1
neurix
  • 4,126
  • 6
  • 46
  • 71

1 Answers1

3

It's not many-to-many relation, you use foreign keys. It's normal setup. To access first picture in template you can use {{ project.projectpicture_set.all.0 }}, it will generate additional query. To avoid it use prefetch_related.

sneawo
  • 3,543
  • 1
  • 26
  • 31