Search code examples
pythondjangodjango-modelsdjango-1.4

Django: I want to connect about one-to-many


Django: I want to connect about one-to-many...

enter image description here

What should I do?

from django.db import models

class Note(models.Model)
    content = models.CharField(max_length=20)

class A(models.Model)
    name = models.CharField(max_length=20)
    addr = models.CharField(max_length=20)
    notes = models.ManyToManyField(Note) # ...? I don't know...

class B(models.Model)
    nickname = models.CharField(max_length=20)
    mobile = models.CharField(max_length=20)
    notes = models.ManyToManyField(Note) # ...? I don't know...

Note model : A model = 1 : N... Note model : B model = 1 : N...

I want to connect Note - A at the same time Note - B...

Please answer me!

Thank you!

Edit 130208 8:36 KST----

Maybe ForegienKey is available...

But my case can't use that.

Because if I want only connection(ex. Note to A), I can do it like the code below.

from django.db import models

class Note(models.Model)
    content = models.CharField(max_length=20)
    conn = models.ForeignKey(A)

class A(models.Model)
    name = models.CharField(max_length=20)
    addr = models.CharField(max_length=20)

But my case need two connection(Note - A, Note - B).

So.... I don't know what should I do...


Solution

  • Use a models.ForeignKey.

    If you want several notes for each instance of A and B you could try something like this:

    from django.db import models
    
        class Note(models.Model):
            content = models.CharField(max_length=20)
            related_to = models.ForeignKey(A_or_B)
    
        class A_or_B(models.Model):
            pass
    
        class A(A_or_B):
            name = models.CharField(max_length=20)
            addr = models.CharField(max_length=20)
    
        class B(A_or_B):
            nickname = models.CharField(max_length=20)
            mobile = models.CharField(max_length=20)
    

    searching the notes that belong to a particular A or B intance would be like this:

    a = A(name="some_name", addr="somewhere")
    a.save()
    a_note = Note(content="blablabla", related_to=a.id)
    a_note.save()
    notes_related_to_a = Note.objects.filter(related_to=a.id)
    links_from_notes_to_a = {note_x.related_to.a for note_x in notes_related_to_a}
    if len(links_from_notes_to_a) and links_from_notes_to_a[0] == a:
        print "It works!"
    

    the related_to attribute of the abstract parent class will have an attribute whose name is the uncapitalized name of the actual class of instance (a or b in this example). This attribute contains the instance of A or B from where you can access the right attributes.

    Check this part of the documentation for more info.