Django - designing model relationships - admin interface and built-in interface

I think my understanding of Django FK and admin is a bit erroneous, so I would appreciate any data on how to simulate the case below.

First, we have common Address objects. Then we have User, each of which has UserProfile. Thanks to this, users belong to departments and also have addresses.

Departments themselves may also have several addresses, as well as the head of the department. So it could be something like this (now I'm just hacking):

class Address(models.Model):
    street_address = models.CharField(max_length=20)
    etc...

class Department(models.Model):
    name = models.CharField(max_lenght=20)
    head_of_department = models.OneToOneField(User)
    address = models.ForeignKey(Address)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    address = models.ForeignKey(Address)
    department = models.OneToOneField(Department)

Anyway, firstly, is this the right way to set up relationships?

-, , , , . AddressInline Department.

class AddressInline(admin.TabularInline):
    model = Address

class DepartmentAdmin(admin.ModelAdmin):
    inlines = [AddressInline]

, , :

Exception at /admin/people/department/1/
<class 'people.models.Address'> has no ForeignKey to <class 'people.models.Department'>

Cheers,

+1
2

, , UserProfile Department , ForeignKeys . ForeignKey , ForeignKeys, . , ForeignKey ( inline ).

, , ; ForeignKey on Address UserProfile, Department. (DepartmentAddress, ForeignKey UserAddress, ForeignKey UserProfile). , , , .

- GenericForeignKey , . inline GenericInlineModelAdmin. . , , ; , , , .

+2

, , :

A department has one to many addresses

A department has one and only one user (as head of department)

A user (through his profile) belongs to one to many departments

A user (through his profile) has one to many addresses

, , , , , ; , :

class Department(models.Model):
    name = models.CharField(max_lenght=20)
    head_of_department = models.OneToOneField(User)
    address = models.ForeignKey(Address)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    address = models.ForeignKey(Address)
    department = models.OneToOneField(Department)

class Address(models.Model):
    street_address = models.CharField(max_length=20)
    ...

    class Meta:
        abstract = True

class UserAddress(Address):
    user_profile = models.ForeignKey(UserProfile)

class DepartmentAddress(Address):
    department = models.ForeignKey(Department)

.

, , - , , / . ( ), , , .

; .

, , : . inline. , , ; . , , .

. . , Author has many Books , .

0

Source: https://habr.com/ru/post/1729020/


All Articles