views:

282

answers:

1

I'm trying to create a django database that records all my comic purchases, and I've hit a few problems. I'm trying to model the relationship between a comic issue and the artists that work on it.

A comic issue has one or more artists working on the issue, and an artist will work on more than a single issue. In addition, the artist has a role relating to what they did on the comic – creator (all the work on that issue), writer (wrote the script), drawer (drew the complete comic), pencils, inks, colours or text, and there may be several artists in a given role.

This gives me a database model like: Database model

I then translate this into the following Django model. As I require additional data on the relationship, I believe I have to use a separate class to handle the relationship, and hold the additional

class Artist(models.Model):
    name = models.CharField(max_length = 100)

    def __unicode__(self):
        return self.name

class ComicIssue(models.Model):
    issue_number = models.IntegerField()
    title = models.TextField()
    artists = models.ManyToManyField(Artist, through='IssueArtist')

    def __unicode__(self):
        return u'issue = %s, %s' % (self.issue_number, self.title)

class IssueArtist(models.Model):
    roles = ( (0, "--------"),
              (1, "Creator"),
              (2, "Writer"),
              (3, "Drawer"),
              (4, "Pencils"),
              (5, "Inks"),
              (6, "Colours"),
              (7, "Text"),
            )
    artist = models.ForeignKey(Artist)
    issue = models.ForeignKey(ComicIssue)
    role = models.IntegerField(choices = roles)

My questions are:

1) Does this seem a correct way of modelling this?

2) If I don't use the through='IssueArtist' feature, I can add relationships by using the artists.add() function. If I do use this, I get an error 'ManyRelatedManager' object has no attribute 'add'. Do I have to manually manage the relationship by creating IssueArtist() instances, and explicitly searching the relationship table? NB. I am using Django 1.0, at the moment

+7  A: 

Hi Simon,

I recommend you check out the section "EXTRA FIELDS ON MANY-TO-MANY RELATIONSHIPS" in the Django documentation - it covers exactly your question.

1: yes, creating an intermediary model is the way to go.

2: From the documentation: "Unlike normal many-to-many fields, you can't use add, create, or assignment to create relationships" - Instead, for adding Artist to an Issue, do it from the intermediary model:

some_artist = Artist.objects.get(name='some name')
some_issue = Issue.objects.get(tile='some tite')
a = IssueArtist.objects.create(artist= some_artist, issue = some_issue, role=1)
a.save()

Hope this helps,

Martin

Hoff
That link is precisely what I was looking for and failing to find. I think I need to look at my search skills.
Simon Callan