Search code examples
pythondatabasedjangomodelsdjango-orm

django model help involving m2m and foreignkey


Ok so this may be really easy for someone else to solve but i'm really confused on how to go about solving this.

So to start, i have a model A that has multiple fields that have many-to-many relationships to specific tables. So for example

class A(models.Model):
    field1 = models.ManyToMany('field1Collection')
    field2 = models.ManyToMany(field2Collection')

class field1Collection(models.Model):
    description = models.TextField()

class field2Collection(models.Model):
    description = models.TextFIeld()

Anyway this is what i'm trying to accomplish. I need to write another model that can hold a ranking system. So for example, i want to create a record where i can define

I have x number of ranks (3 for example):

  1. field1Collection Object 3
  2. field2Collection Object 6
  3. field1Collection Object 2

So i basically want to be able to select objects from my field1Collection and field2Collection tables and assign them ranks. I tried thinking up schemes using foreignkeys and m2m fields but they all go wrong because the model needs to know "ahead" of time which collection set i need to reference. Does this many sense? can anyone help?


Solution

  • You can solve this using GenericForeignKey relationship

    from django.db import models
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.contenttypes import generic
    
    class RankItem(models.Model):
        rank = models.IntegerField()
        content_type = models.ForeignKey(ContentType)
        object_id = models.PositiveIntegerField()
        content_object = generic.GenericForeignKey('content_type', 'object_id')
    
        def __unicode__(self):
            return self.rank
    

    A normal ForeignKey can only "point to" one other model, which means that if the RankItem model used a ForeignKey it would have to choose one and only one model to store tags for. The contenttypes application provides a special field type which works around this and allows the relationship to be with any model