[Fixed]-Connect one model's ManyToManyField with another model's ForeignKey

1👍

You could do it the following way, and Django should automatically add a reverse relation. Hence, no need to add album as foreign key to your Photo model. Doing this you get access to “albums” from your Photo model.

class Photo(models.Model):
    name = models.CharField(max_length=64)

class Album(models.Model):
    name = models.CharField(max_length=64)
    photoItems = models.ManyToManyField(Photo, related_name='albums')

Shell:

>>> photo1=Photo(name="photo number 1")
>>> photo2=Photo(name="photo number 2")
>>> photo1.save()
>>> photo2.save()
>>> album=Album(name="album1")
>>> album.save()
>>> album.photoItems.add(photo1,photo2)
>>> photo1.albums.get().name
'album1'

Leave a comment