Search code examples
djangoormmodels

Django model field relating to a few models


Imagine a 5x5 grid (map), every field of it represents a certain object (it can be a monster, a tree etc.)

So, here we have:

class Field(Model):
    x = y = PositiveIntegerField()
    content = ...(?)

Here the problem arises. Here is the alternative, but I think this way is too messy, especially if I have many different content ids.

class Field(Model):
    x = y = PositiveIntegerField()
    content = PositiveIntegerField()

    monster_rel = ForeignKey(Monster, null=True, blank=True)
    building_rel = ForeignKey(Monster, null=True, blank=True)
    nature_obj_rel = ForeignKey(Monster, null=True, blank=True)

and then in a view:

f = Field.objects.get(pk=1)
if f.content == 1:
    print "Monster %s of level %d" % (f.monster_rel.name, f.monster_rel.level)
elif f.content == 2:
    print "This is a %s" % f.building_rel.type
...

Is there a better solution for this?

EDIT I would like fields like:

content_id = IntegerField()
content_rel = FieldRelatedToModelByContentId()

Solution

  • Well, sounds like generic relations is exactly what you're looking for.