views:

126

answers:

1

My question is pretty much the same as this question, except that ALL relationships should be many-to-many.

I have the following classes in my models.py (somewhat simplified):

class Profile(models.Model):
    # Extending the built in User model  
    user = models.ForeignKey(User, unique=True)  
    birthday = models.DateField()

class Media(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(max_length=2000)

class Role(models.Model):
    name = models.CharField(max_length=50)


What I want is a junction table that looks something like this:

CREATE TABLE `media_roles` (
    `media_id` bigint(20) unsigned NOT NULL,
    `profile_id` bigint(20) unsigned NOT NULL,
    `role_id` bigint(20) unsigned NOT NULL
)


  • John Doe - Director, Writer, Producer
  • Jane Doe - Executive Producer
  • ...

This is what I've used so far:

class MediaRole(models.Model):
    media = models.ForeignKey(Media)
    user = models.ForeignKey(Profile)
    role = models.ForeignKey(Role)


But isn't there any better way of doing this, not involving the creation of a separate class in the model?

A: 

What about separating the two m2m relationships?

class Profile(models.Model):
    ...
    medias = models.ManyToManyField(Media, related_name='profiles')
    roles = models.ManyToManyField(Role, related_name='profiles')

In this way Django create two association tables for you, and you can utilize the convenient related fields like this:

profile = Profile.objects.get(user=someone)
print profile.medias.all()
print profile.roles.all()
Satoru.Logic
How would that make it possible to assign multiple Roles per Profile per Media upload? I'm confused
Saosin
@Saosin, it sounds like you want a m2m relationship between `Profile` and `Media`, and for each of these relationship there are many `Roles`. If so, you may try creating an association table of `Profile` and `Media`, and then make `roles` a foreignkey.
Satoru.Logic
Using an intermediate model with 'through' like this: http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships? Since there may only be two foreign keys in it - one pointing to the source model and the other to target that wouldn't work. Or am I misunderstanding the documentation?
Saosin