views:

22

answers:

1

I have two models that has a manytomany relationship with a 'through' table in some way?

class Bike(models.Model):
   nickname = models.CharField(max_length=40)
   users    = models.ManyToManyField(User, through='bike.BikeUser')

The BikeUser class

class BikeUser(models.Model):
   bike     = models.ForeignKey(Bike)
   user     = models.ForeignKey(User)
   comment  = models.CharField(max_length=140)

I would like to add functionality to the Bike class for working with users, is there a best practice way of doing this. I would like to avoid adding too many methods to the Bike class and rather have some kind of manager to work through

Something like:

bike.bikeusers_set.commonMethod()

or

bike.bikeusers.commonMethod()

What would be the best way to accomplish this?

+3  A: 

Once you have the BikeUser model, you can add a custom manager to the model.

Something like:

class BikeUserManager(models.Manager):
    def commonMethod():
        pass

class BikeUser(models.Model):
   bike     = models.ForeignKey(Bike)
   user     = models.ForeignKey(User)
   comment  = models.CharField(max_length=140)
   objects  = BikeUserManager()

But you can only use it from the BikeUser Model:

BikeUser.objects.commonMethod()

What you want is to use this manager as a related manager: http://docs.djangoproject.com/en/dev/topics/db/managers/#controlling-automatic-manager-types

Add the use_for_related_fields=True to the manager class.

class MyManager(models.Manager):
    use_for_related_fields = True
OmerGertel
Thank you, that worked like a charm! Howerver, if I call the manager from an instanciated Bikebike.bikeuser_set.commonMethod()How do I access the "bike" from within the commonMethod?(should this be a new question?)
Joelbitar
I think you'll have to add it as a function parameter: def commonMethod(self,bike) and use it like this: bike.bikeuser_set.commonMethod(bike)
OmerGertel
Thats what I'v been doing, I thought there was a better way, thank you very much anyways!
Joelbitar