HOWTO: Create a ManyToMany Relationship?

28 views
Skip to first unread message

Timothy W. Cook

unread,
Oct 22, 2013, 5:59:14 PM10/22/13
to django...@googlegroups.com
Can someone point me to where this is explained in the docs (1.6)?

I have a ManyToMany relationship in my models between Author and Paper.  

I am processing an XML file to create records for Papers.

I want to check if an Author exists and if not create the record. 

This was quite easy for Foreign Key relationships.  But I can't get my head around how to do this for ManyToMany.  All of my Authors are created correctly.  But none are automatically selected for the Papers. 

Some code:

class AuthorManager(models.Manager):
    def create_author(self, name, email, affl):
        a = self.create(name=name, email=email, affiliation=affl)
        a.save()
        return a

class Author(models.Model):
    name = models.CharField("Name", max_length=255, db_index=True, null=True, blank=True, help_text="")
    email = models.EmailField("Email", max_length=255, null=True, blank=True, help_text="")
    affiliation = models.CharField("Affiliation", max_length=255, null=True, blank=True, help_text="")

    objects = AuthorManager()

    def __str__(self):
        return self.name


def import_pubmed_xml(obj, f):
...
        p = Paper.objects.create_paper(ptitle,rid,jid,jyear,jvol,jissue,lang)

        #authors
        affl = article.xpath("./Affiliation/text()")
        if affl: affl = affl[0]
        else: affl = 'unknown'
        affl = affl.strip()

        authorlist = article.xpath("./AuthorList")
        for authorentry in authorlist:
            for author in authorentry:
                lname = author.xpath("./LastName/text()")
                if lname:
                    lname = lname[0]
                else:
                    lname = 'unknown'
                fname = author.xpath("./ForeName/text()")
                if fname:
                    fname = fname[0]
                else:
                    fname = 'unknown'
                initials = author.xpath("./Initials/text()")
                if initials:
                    initials = initials[0]
                else:
                    initials = ''

                a_name = (lname +', '+fname + ' ' +initials).strip()
                print(a_name)
                email = ''
                #need to lookup Author by name then check affiliation. If not found then create it.
                try:
                    a = Author.objects.get(name=a_name)
                    p.authors.id = a.id
                    p.save()
                except ObjectDoesNotExist:
                    a = Author.objects.create_author(a_name, email, affl)
                    p.authors.id = a.id
                    p.save()
===================================================

Thanks in Advance,
Tim





--
MLHIM VIP Signup: http://goo.gl/22B0U
============================================
Timothy Cook, MSc           +55 21 94711995
MLHIM http://www.mlhim.org
Like Us on FB: https://www.facebook.com/mlhim2
Circle us on G+: http://goo.gl/44EV5
Google Scholar: http://goo.gl/MMZ1o
LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook

Pepsodent Cola

unread,
Oct 22, 2013, 8:51:13 PM10/22/13
to django...@googlegroups.com
I'm a beginner so I can only answer your first question.  The below link has helped me with 1:M and N:M relationship experiments.

Can someone point me to where this is explained in the docs (1.6)?

Mike Dewhirst

unread,
Oct 23, 2013, 2:33:16 AM10/23/13
to django...@googlegroups.com
On 23/10/2013 11:51am, Pepsodent Cola wrote:
> I'm a beginner so I can only answer your first question. The below link
> has helped me with 1:M and N:M relationship experiments.
>
> Can someone point me to where this is explained in the docs (1.6)?
>
>
> https://docs.djangoproject.com/en/1.6/topics/db/examples/

https://docs.djangoproject.com/en/1.6/ref/models/fields/#manytomanyfield

Also, a couple of paragraphs below that ...

https://docs.djangoproject.com/en/1.6/ref/models/fields/#django.db.models.ManyToManyField.through

... where it explains that you can have your own table for the m2m
relationship if you want to store data about the relationship itself.

For this to make sense you need to declare a model class for that table
with fields for the extra data. Note that this isn't necessary for
ordinary m2m relationships because Django does it implicitly.

Anyway, if you make an extra table, it needs a FK to each of the other
tables. Maybe like ...

class AuthorPaper(models.Model):
author = models.ForeignKey('Author')
paper = models.ForeignKey('Paper')
gossip = models.TextField()

Now this being a model in your own code means you can deal with it in
more or less the same way as all the other models in your views etc.

I haven't read the code below in any detail so this is probably off the
mark but there is a get_or_create method which might be useful.

https://docs.djangoproject.com/en/1.5/ref/models/querysets/#django.db.models.query.QuerySet.get_or_create

hth

Mike

>
>
>
>
>
> On Tuesday, October 22, 2013 11:59:14 PM UTC+2, Timothy W. Cook wrote:
>
> Can someone point me to where this is explained in the docs (1.6)?
>
> I have a ManyToMany relationship in my models between Author and Paper.
>
> I am processing an XML file to create records for Papers.
>
> I want to check if an Author exists and if not create the record.
>
> This was quite easy for Foreign Key relationships. But I can't get
> my head around how to do this for ManyToMany. All of my Authors are
> created correctly. But none are automatically selected for the Papers.
>
> Some code:
>
> class AuthorManager(models.Manager):
> def create_author(self, name, email, affl):
> a = self.create(name=name, email=email, affiliation=affl)
> a.save()
> return a
>
> class Author(models.Model):
> name = models.CharField("Name", max_length=255, db_index=True,
> null=True, blank=True, help_text="")
> email = models.EmailField("Email", max_length=255, null=True,
> blank=True, help_text="")
> affiliation = models.CharField("Affiliation", max_length=255,
> null=True, blank=True, help_text="")
>
> objects = AuthorManager()
>
> def __str__(self):
> return self.name <http://self.name>
> p.authors.id <http://p.authors.id> = a.id <http://a.id>
> p.save()
> except ObjectDoesNotExist:
> a = Author.objects.create_author(a_name, email,
> affl)
> p.authors.id <http://p.authors.id> = a.id <http://a.id>
> p.save()
> ===================================================
>
> Thanks in Advance,
> Tim
>
>
>
>
>
> --
> MLHIM VIP Signup: http://goo.gl/22B0U
> ============================================
> Timothy Cook, MSc +55 21 94711995
> MLHIM http://www.mlhim.org
> Like Us on FB: https://www.facebook.com/mlhim2
> <https://www.facebook.com/mlhim2>
> Circle us on G+: http://goo.gl/44EV5
> Google Scholar: http://goo.gl/MMZ1o
> LinkedIn Profile:http://www.linkedin.com/in/timothywaynecook
> <http://www.linkedin.com/in/timothywaynecook>
>
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/ff993a02-baad-4a7d-ad39-529ddafd8861%40googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

Timothy W. Cook

unread,
Oct 23, 2013, 5:29:48 AM10/23/13
to django...@googlegroups.com
Thanks for the link.
The add() method was what I was missing.

Changing the one line to p.authors.add(a.id), fixed it.




--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ff993a02-baad-4a7d-ad39-529ddafd8861%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Timothy W. Cook

unread,
Oct 23, 2013, 5:33:22 AM10/23/13
to django...@googlegroups.com
Thanks Mike. Yes, the get_or_create works great in my ForeignKey situation (Paper in a Journal) but I am not so sure it is a good choice here.  For one thing the incoming data makes it very difficult to filter out Authors.  There isn't enough real information to tell if it is the same person or not.  :-(  So, I have to do multiple checks and take a guess. 




--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/groups/opt_out.

--
MLHIM VIP Signup: http://goo.gl/22B0U
============================================
Timothy Cook, MSc           +55 21 94711995
MLHIM http://www.mlhim.org
Like Us on FB: https://www.facebook.com/mlhim2
Reply all
Reply to author
Forward
0 new messages