Frage

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)
War es hilfreich?

Lösung 2

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()

Andere Tipps

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top