1

I have to models

class Parent(object):
     text_field = models.TextField()  
     boolean_field = models.BooleanField()

class Child(Parent):
     another_text_field = models.TextField()

With the following ModelAdmin

class ChildAdmin(admin.ModelAdmin):                         
    pass 


admin.site.register(Child, ChildAdmin)       

I currently see all fields in the admin page, i.e. text_field, boolean_field, and another_text_field.

Question: How can I get a parent select field and exclude text_field and boolean_field (for latter I guess I can use exclude).

Current Solution: I add a Form and use its clean method to set the parent field. text_field and boolean_field can be excluded by addind it to the ModelAdmin's excluded variable.

ezdazuzena
  • 6,120
  • 6
  • 41
  • 71

2 Answers2

0

simply overwrite fields

class Child(Parent):
    another_text_field = models.TextField()
    text_field = None
    boolean_field = None

if you want to use inheritance in django models use abstract models please.

katoozi
  • 388
  • 2
  • 6
0

I am not sure if it is really necessary to use model inheritance. if not, you may consider using OneToOneField without model inheritance.

Example using OneToOneField:

models.py

class Parent(models.Model):
    text_field = models.TextField()  
    boolean_field = models.BooleanField()

class Child(models.Model):
    parent = models.OneToOneField(Parent,
        on_delete=models.CASCADE,
        primary_key=True)
    child_field = models.TextField()

admin.py

@admin.register(Parent)
class ParentAdmin(admin.ModelAdmin):
    pass

doing so you can see a drop down menu for picking Parent instance at child admin page. but meanwhile, you lose one 'benefit' of using inheritance, which is the availability of Parent field in Child

as mentioned in the docs,

All of the fields of Place will also be available in Restaurant, although the data will reside in a different database table.

but there is a easy fix for that, just use something like Child.objects.filter(parent__text_field="something"). Query performance should be the same (I guess) since implementation in db are basically the same for these two approaches (both use separated table) (please correct if I am wrong)

Apart from from this and admin display behavior, I am not sure how these two approaches (your approach and this answer) are differed.

Bensoft
  • 1
  • 3