Django Generic ForeignKey vs Multiple Foreign Key Fields

1,472 views
Skip to first unread message

Arun Prabhakar

unread,
Apr 8, 2013, 5:32:49 AM4/8/13
to django...@googlegroups.com
# I have 2 models, say A and B
class A(models.Model):
    pass

class B(models.Model):
    pass

"""
Now my query is which of the following would you choose and why?
"""

class GenericFK(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

#-- vs --

class MultipleFK(models.Model):
a = models.ForeignKey(A, null=True)
  b = models.ForeignKey(B, null=True)


Thank you.


Martin J. Laubach

unread,
Apr 8, 2013, 5:49:07 AM4/8/13
to django...@googlegroups.com
  It's simply a question of what you want to model.

  GenericFK means for each instance "I have a relationship with some other (undefined) entity". MultipleFK means "I have relationships with both well-known entities A and B". Totally different things.

  Cheers,

    mjl


Arun Prabhakar

unread,
Apr 8, 2013, 6:34:50 AM4/8/13
to django...@googlegroups.com
Hi Martin,

A and B are known, and more can come in the future, so it would seem generic is the way to go, but then I dont want to reference on all tables in django.
But using the FK has problem of introducing alter tables later.

Confused about going with which approach.

What do you suggest?

Javier Guerra Giraldez

unread,
Apr 8, 2013, 9:43:55 AM4/8/13
to django...@googlegroups.com
On Mon, Apr 8, 2013 at 5:34 AM, Arun Prabhakar <arun...@gmail.com> wrote:
> more can come in the future

that's reason enough to use Generic relations


--
Javier

Javier Guerra Giraldez

unread,
Apr 8, 2013, 9:45:16 AM4/8/13
to django...@googlegroups.com
(of course, much better would be if you can refactor your data
representation so you can go with a fixed set of tables)

--
Javier
Reply all
Reply to author
Forward
0 new messages