1π
β
I think what you need is ForeignKey
. You can link one Person
object to another one. Just add this:
class Person(models.Model):
...
agent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, related_name='clients')
From now on, you can simply add one Person
as an agent
in another Person
βs field. Usage:
person_1 = Person.objects.create(...)
person_2 = Person.objects.create(..., agent=person_1)
person_1.clients.all()
# <QuerySet [<Person: Person 2>]>
person_2 in person_1.clients.all()
# True
person_2.agent
# <Person: Person 1>
person_2.agent.related_entity.entity_type
# 'Company' / 'Person'
You can access related object by simple .agent
or reverse relation of all clients with the related_name
you want to use, in my example itβs .clients
. Just remember, that reverse relation is always a QuerySet
, because one agent can have many clients, but every client can have one agent. Relationhips are very powerful in Django, follow this DOCS for details.
π€NixonSparrow
Source:stackexchange.com