views:

618

answers:

2

hey,

i want to use 2 model in one foreignkey

it means;

i have 2 model named screencasts and articles. and i have a fave model, for favouriting this model entrys. can i use model dynamicly ?

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 it possible ?

+6  A: 

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 smthg 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

vikingosegundo
+2  A: 

Here's an approach. (Note that the models are singular, Django automatically pluralizes for you.)

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

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

FAVE_CHOICES = ( 
    ('A','Article'),
    ('C','Cast'),
)
class Fave(models.Model):
    type_of_fave = models=CharField( max_length=1, choices=FAVE_CHOICES )
    cast = models.ForeignKey(Casts,null=True)
    article= models.ForeigKey(Articles,null=True)
    user = models.ForeignKey(User,unique=True)

This rarely presents profound problems. It may require some clever class methods, depending on your use cases.

S.Lott
+1 I think generic contenttypes, as in accepted answer, are better for "pluggable" models where you don't know anything about the relations. Your answer is better for situations where you have control and complete knowledge of all the models. Better means easier to write queries and less hits on the database.
Van Gale
You forgot "null=True" in the cast and article FK field args because each Fave instance will only not set the one FK field to None which corresponds to the setting in the type_of_fave field