Anakin Anakin - 6 months ago 22
Python Question

How to use dynamic foreignkey in Django?

I want to connect a single

ForeignKey
to two different models.

For example:

I have two models named
Casts
and
Articles
, and a third model,
Faves
, for favoriting either of the other models. How can I make the
ForeignKey
dynamic?

class Articles(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()

class Casts(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()

class Faves(models.Model):
post = models.ForeignKey(**---CASTS-OR-ARTICLES---**)
user = models.ForeignKey(User,unique=True)


Is this possible?

Answer

Here is how I do it:

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic


class Photo(models.Model):
    picture = models.ImageField(null=True, upload_to='./images/')
    caption = models.CharField(_("Optional caption"),max_length=100,null=True, blank=True)

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

class Article(models.Model):
    ....
    images     = generic.GenericRelation(Photo)

You would add something like

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

to Faves and

    generic.GenericRelation(Faves)

to Article and Cast

contenttypes docs

Comments