I have a Django Rest Framework and added the model Groups that I'm trying to relate back to itself, in a ManyToMany field called related_groups. The model changes and the makemigrations script created a new table called group_related_groups (Group was a previously implemented model, with new fields added for relationships).
The new model looks like this:
class Group(models.Model):
"""
Model definition of a Group. Groups are a collection of users (i.e.
Contacts) that share access to a collection of objects (e.g. Shipments).
"""
group_id = models.AutoField(primary_key=True)
group_name = models.CharField(max_length=100)
owner_id = models.ForeignKey('Owner', related_name='groups')
category = models.CharField(max_length=30)
related_groups = models.ManyToManyField('self', blank='true')
What I'm wanting to achieve is the related groups column holds the PKs of associated groups. For example, multiple groups of Students could belong to a single group of Counselors, where the Group model is the establishing factor for all Users. Like:
| id | group_name | owner_id | category |
------------------------------------------
| 1 | students1 | 10 | student |
| 2 | counselors | 10 | counselor |
| 3 | students2 | 10 | student |
....
| 7 | students3 | 10 | student |
and on the group_related_groups table:
| id | from_group_id | to_group_id |
------------------------------------
| 1 | 1 | 2 |
| 2 | 1 | 3 |
| 3 | 1 | 7 |
| 4 | 2 | 1 |
| 5 | 2 | 3 |
| 6 | 2 | 7 |
| 7 | 3 | 1 |
| 8 | 3 | 2 |
| 9 | 3 | 7 |
| 10 | 7 | 1 |
| 11 | 7 | 2 |
| 12 | 7 | 3 |
....................................
Is it possible to create a new group and associate it to existing groups at the same time? The new table created by adding the related_groups field is just a relationship table, right? But it'd require a primary key from the new group to create the association... so, a race condition.
Is there a more accepted pattern for relating a model's members to itself?
Edit: added Django Rest Framework as requirement