[Django]-Django OneToOneField and Admin UI

2๐Ÿ‘

#1

models.py

class BillingAddress(models.Model):
    employee = models.OneToOneField(to=Employee, related_name='billing_address')

class Employee(models.Model):
    # Many more such fields

admin.py

class AddressInline(admin.TabularInline):
    model = BillingAddress
    extra = 1

@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
    inlines = [AddressInline, ]

#2

models.py

class Address(models.Model):
    name = models.CharField(max_length=250)
    employee = models.ForeignKey(to=Employee, related_name='addresses')

class Employee(models.Model):
    # Many more such fields

admin.py

class AddressInline(admin.TabularInline):
    model = Address

@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
    inlines = [AddressInline, ]

Full Example:

models.py

class Company(models.Model):
    pass


class CompanyScheduler(models.Model):
    company = models.OneToOneField(
        to=Company,
        related_name='scheduling',
        on_delete=models.CASCADE,
    )

    start = models.DateField()
    finish = models.DateField()

admin.py

class CompanySchedulerInLine(admin.TabularInline):
    model = CompanySchedulerInLine
    extra = 1


@admin.register(CompanyModelAdmin)
class CompanyModelAdmin(admin.ModelAdmin):

    inlines = [
        SchedulerInLine,
    ]

UI

enter image description here

๐Ÿ‘คSonic Park

Leave a comment