2

Say we have a model with two self-recursive relations:

class Article(Item): # Item in this case is an abstract class
    date = models.DateField()
    parent = models.OneToOneField('self', null=True, blank=True)
    subatricles = models.ForeignKey('self', null=True, blank=True, related_name='subs')

Article acts here as a node - it can has many children (if supplied) and one parent (if any). However, when I register my model in Django's admin my subatricles are shown as "one-to-one' - in both cases there are choice boxes but in the latter multiple values cannot be selected, though.

How can I add children via the admin pane to this Article object and later list them?

What I would like to have is this: instead of normal drop-down.

Thanks.

laszchamachla
  • 763
  • 9
  • 21

1 Answers1

6

You only need one field parent with subarticles as related_name to provide the reverse lookup:

class Article(Item): # Item in this case is an abstract class
    date = models.DateField()
    parent = models.ForeignKey('self', null=True, blank=True, related_name='subarticles')

so if you have an article object and you want to get its parent, use:

article.parent

if you want to get its children, you use:

article.subarticles

In the admin interface to show the subarticles the easiest way is to use the InlineModelAdmin:

class ArticleInline(admin.StackedInline):
    model = Article

class ArticleAdmin(admin.ModelAdmin):
    inlines = [
        ArticleInline,
    ]
Sergey Golovchenko
  • 18,203
  • 15
  • 55
  • 72
  • Thanks a lot for your explanation - it helped me a lot. I have one little (I hope the last) problem, though. If I specify fields to show: `fieldsets = [(None, {'fields': ... 'parent', 'subatricles']})'` Django shows me `ImproperlyConfigured at ... 'ArticleAdmin.fieldsets[0][1]['fields']' refers to field 'subarticles' that is missing from the form.` How can I avoid this? I want to be able to add existing articles to article's children selecting them from multichoice box. – laszchamachla Sep 30 '11 at 21:52
  • @Up - I need similar solution as here: [link](http://stackoverflow.com/questions/1691299/can-django-admin-handle-a-one-to-many-relationship-via-related-name/5018393#5018393) for ManyToMany problem in Django Admin: – laszchamachla Oct 01 '11 at 12:57
  • You will be able to add children to article, that's what the "inline" is for. By the way if you only have one fieldset no need to specify it at all. Take the "fieldsets" out of your admin entirely, is it working now? – Sergey Golovchenko Oct 02 '11 at 04:37