python-3.xdjangodjango-modelsmodelmanytomanyfield

ManytoManyField Django : how to call models in methods?


I need help for something, I want to call models with ManyToManyField. I want to have method to get Class A from Class B, and another in Class B to get Class A.

here's my (shortened) code :

class Licence(models.Model):
    name = models.CharField(max_length=64)
    picture = models.ImageField(upload_to='finder/static/finder/img/licence/',null=True, blank=True)
    description = models.TextField(null=True, blank=True)

    #returns a list of games from this license
    def getGamesOnThisLicence(self):

        #i don't know how to proceed

class Game(models.Model):
    name = models.CharField(max_length=64)
    description = models.TextField()
    release_date = models.DateField(null=True, blank=True)
    licence = models.ManyToManyField(Licence, blank=True, null=True)

    #return name of licence to which the game belongs
    def getLicenceName(self):
        return self.licence.name

Solution

  • You can access the Games with:

    my_license.game_set.all()

    so you can use self in the getGamesOnThisLicense, but probably there is not much gain to define a function since this makes accessing the Games already quite convenient.

    Perhaps you however want to transform the ManyToManyField into a ForeignKey to License since self.license.name makes not much sense: for a ManyToManyField, self.license is a Manager over License objects that can manage zero, one or more Licenses, so you can not use self.license.name.