Add fields and extend Django's built-in Group
model using a OneToOneField
(i.e. a profile model). In this example, we add a UUIDField
. Whenever a new group is created, we automatically (via signals) create a corresponding Role
record referencing the newly created group. Whenever a Group is deleted, the corresponding Role is deleted as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | from uuid import uuid4 from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver class Role(models.Model): """Extension of Django's built-in Group model Adds a UUID field to Django's built-in Group model. """ uuid = models.UUIDField( auto_created=True, default=uuid4, editable=False, help_text="object ID", primary_key=True, unique=True, ) group = models.OneToOneField(Group, on_delete=models.CASCADE) def __str__(self): return f"{self.group.name}" @receiver(post_save, sender=Group) def create_role(sender, instance, created, **kwargs): if created: Role.objects.create(group=instance) |
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.