How to deal with circular relationship in Django models?
I'm trying to write a basic DB to offer my photographs. It seemed so simple, but I just can't wrap my head around this, despite thinking for a couple of weeks. I'm trying to combine multiple models that link to each other.
Photo: Files with some stored data
Person: Data about a person that appears in a photo / has mad a Quote
Quote: Something a Person has said and needs to be attached to Photos
(the quote does not belong to all photos of that person, but rather a specific set)
Offer: An overview that has all the quotes with one Photo as a thumbnail and all the Photos
(some photos might have the same quote, but it should only appear once)
As a mockup and because people here really love to see some code first I made this:
class Quote:
person = models.ForeignKey("Person")
photos = models.ManyToManyField("Photo")
class Person:
photo = models.ForeignKey("Photo")
class Photo:
pass
class Offer:
quotes = models.ManyToManyField("Quote")
photos = models.ManyToManyField("Photo")
Please take the code above as an illustration, because I already don't know how to tackle this. I tried multiple different versions, but there is always some case that doesn't get covered. In the above example the problem is: Person and Quote are independently attached to Photos. But there can't be a Quote without that Person being in there. So some information is doubled and might disagree. I also tried to using "through=" to bring People and Quotes together, but then ran into other problems.
Can you recommend any good tutorials or give me a hint how to deal with these kind of 'messy' relationships?
Thank you, Michael
Hope I got things right. Following is a diagram showing how I would set up this class structure.
- Person: each person has multiple quotes and is part of multiple photos
- Photo: each photo is part of multiple photosets
- Quote: each quote references one photoset
- Photoset_Photos: many to many structure to connect multiple photosets with multiple photos
- Photoset: each photoset does include multiple photos and can be referenced by multiple quotes
- Offer: one offer references multiple photosets, with this reference you can get all quotes to their photosets and all photos