Django Model Inheritance. Hiding or removing fields
Asked Answered
B

5

10

I want to inherit a model class from some 3rd party code. I won't be using some of the fields but want my client to be able to edit the model in Admin. Is the best bet to hide them from Admin or can I actually prevent them being created in the first place?

Additionally - what can I do if one of the unwanted fields is required? My first thought is to override the save method and just put in a default value.

Buhler answered 4/3, 2009 at 17:49 Comment(0)
E
3

If you are inheriting the model then it is probably not wise to attempt to hide or disable any existing fields. The best thing you could probably do is exactly what you suggested: override save() and handle your logic in there.

Evangelize answered 4/3, 2009 at 17:57 Comment(0)
V
3

Rather than inherit, consider using customized Forms.

  1. You can eliminate fields from display that are still in the model.

  2. You can validate and provide default values in the form's clean() method.

See http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin

Valentinavalentine answered 4/3, 2009 at 18:20 Comment(0)
I
3

You can control the fields that are editable in admin.

From the Django docs:

If you want a form for the Author model that includes only the name and title fields, you would specify fields or exclude like this:

class AuthorAdmin(admin.ModelAdmin):
    fields = ('name', 'title')

class AuthorAdmin(admin.ModelAdmin):
    exclude = ('birth_date',)

http://docs.djangoproject.com/en/dev/ref/contrib/admin/

Inge answered 4/3, 2009 at 19:2 Comment(0)
E
1

As long as that 3rd party model you're inheriting from is an abstract model and you're sure the field is not needed, you can remove it on a model level with the following declaration:

class MyChild(ThirdPartyModel):
   unimportant_field = None

That way it won't even exist in the database and you certainly won't need any further modifications in Admin.

Emilieemiline answered 25/10, 2021 at 12:29 Comment(0)
B
0

You can remove fields by Setting "None" to them.

For example, there is "Student" class which extends the 3rd party model "Person" then to remove "name" and "age" fields from "Student" class, set "None" to them in "Student" class as shown below:

from django.db import models

class Person(models.Model):
   name = models.CharField(max_length=100)
   age = models.IntegerField()

   class Meta:
      abstract = True

class Student(Person):
   name = None # Here
   age = None # Here

In addition, you cannot remove "id" field from "Student" class even if you set "None" to it in "Student" class as shown below:

from django.db import models

class Person(models.Model):
   name = models.CharField(max_length=100)
   age = models.IntegerField()

   class Meta:
      abstract = True

class Student(Person):
   id = None # Here
Blanka answered 22/5, 2022 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.