Reputation: 3011
lets say I want to model the following:
There Are Texts, that can have many Quotes, each Quote is Part of one Text. On top of that, each Quote is on a specific Page of one Text.
I found that there is an through relationship Model for ManyToMany fields, that would allow me to add Attributes to the relation (like the Option to define a Page). Is that also possible on the OneToMany-Relationship? How can I model that in django?
That is what I have so far
class Text(models.Model):
title = models.CharField(max_length=100)
class Quote(models.Model):
text = models.TextField()
source = models.ForeignKey(Text)
Upvotes: 0
Views: 63
Reputation: 174622
How about this?
class Quote(models.Model):
text = models.TextField()
page = models.IntegerField()
class Text(models.Model):
title = models.CharField(max_length=100)
quote = models.ManyToMany(Quote, blank=True, null=True)
Sample usage:
t = Text.objects.create('My Text')
q = Quote.objects.create('Quote 1', 2)
q2 = Quote.objects.create('Quote 2', 2)
t.quote_set.add(q)
t.quote_set.add(q2)
t.save()
Upvotes: 1
Reputation: 2482
You should create a Page
object with a ForeignKey to Text
, and then the source
ForeignKey of Quote
should target a Page
object.
Something like:
class Text(models.Model):
title = models.CharField(max_length=100)
class Page(models.Model):
number = models.IntegerField()
text = models.ForeignKey(Text)
class Quote(models.Model):
text = models.TextField()
page = models.ForeignKey(Page)
You can find out the Text
instance for a given Quote
traversing the page relation:
quote.page.text
Upvotes: 2