0

Class Folder inherits from class Item, which has a foreign key to Folder:

class Item(models.Model):
    # some fields
    folder = models.ForeignKey('Folder')

class Folder(Item):
    # some fields

When I try to run this, I get the error:

app.item: 'folder' has a relation with model Folder, which has either not been installed or is abstract

I thought the correct thing to do here was to put the model name in quotes, which I have done, but it doesn't seem to help. What should I do to make this work?

Edit: Clarified question using meaningful class names

hughes
  • 5,595
  • 3
  • 39
  • 55
  • 1
    https://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance – dm03514 Nov 15 '12 at 18:14
  • I've read that, and didn't find it to cover this case. `A` is not an abstract class. I know that if an instance of `B` is an `A`, I can get it with `A.b`, but I'm trying to link it to a different object entirely. – hughes Nov 15 '12 at 18:20
  • For starters this is conceptually wrong. `A` has a ForeignKey to `B` and `B` inherits `A` *along* with `A`'s reference to `B` again. – rantanplan Nov 15 '12 at 18:21
  • That is intended. I want both `A` and `B` to have a ForeignKey to `B`. – hughes Nov 15 '12 at 18:25
  • I don't think you understand. This is an infinite relationship definition. None of the 2 models manage to get defined. – rantanplan Nov 15 '12 at 18:27
  • Ah, I think I get it now. Perhaps what I need is an abstract class with a ForeignKey to B that both A and B inherit from? – hughes Nov 15 '12 at 18:29
  • It would be nice to describe the real world situation you're trying to describe in your database, because I can't tell what exactly you need. – rantanplan Nov 15 '12 at 18:31
  • I have Items (`A`), some of which are Folders (`B`). I want both classes to have a reference to at most one Folder, so that Items and Folders can be in Folders. – hughes Nov 15 '12 at 18:34

1 Answers1

1

I have Items (A), some of which are Folders (B). I want both classes to have a reference to at most one Folder

It doesn't make much sense(to me) what you're trying to do but this can be achieved as follows:

class Item(models.Model):
    # some fields
    is_folder = models.BooleanField(default=False)
    some_other_folder = models.ForeignKey('self', null=True, blank=True)

And then check with python code that if is_folder==False, that some_other_folder is not None(null).

So actually you don't need 2 models.

rantanplan
  • 7,283
  • 1
  • 24
  • 45