How to use dynamic foreignkey in Django?

前端 未结 2 1651
陌清茗
陌清茗 2020-12-12 13:45

I want to connect a single ForeignKey to two different models.

For example:

I have two models named Casts and Articles

相关标签:
2条回答
  • 2020-12-12 14:34

    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.

    0 讨论(0)
  • 2020-12-12 14:35

    Here is how I do it:

    from django.contrib.contenttypes.models import ContentType
    from django.contrib.contenttypes import fields
    
    
    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 = fields.GenericForeignKey('content_type', 'object_id')
    
    class Article(models.Model):
        ....
        images     = fields.GenericRelation(Photo)
    

    You would add something like

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

    to Faves and

        fields.GenericRelation(Faves)
    

    to Article and Cast

    contenttypes docs

    0 讨论(0)
提交回复
热议问题