Dmitriy Kuzminov
Dmitriy Kuzminov

Reputation: 189

Connect one model's ManyToManyField with another model's ForeignKey

let I have a model with ForeignKey to another:

class Photo(models.Model):
    name = models.CharField(max_length=64)
    album = models.ForeignKey('Album')

And that 'Album' model must to connect this photo's objects to its ManyToManyField automatically:

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

And the question is how can I do this?

Upvotes: 0

Views: 69

Answers (1)

Purpamine
Purpamine

Reputation: 141

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'

Upvotes: 1

Related Questions