Editing dynamic choice fields in Django

141 Views Asked by At

I have a standard Django blog with a Post model, only on the model I have added a ManyToManyField for approvers, the idea being that the backend passes the post to 2 or more approvers to confirm the content before it is published.

class Post(models.Model):
    author = models.ForeignKey(
        get_user_model(), null=True, on_delete=models.SET_NULL)
    title = models.CharField(max_length=30)
    content = models.CharField(max_length=30)
    approvers = models.ManyToManyField(Approvers)

I will probably learn towards something like django-fsm to create a finite state machine for the Post model to govern whether it is draft/in approval/published, but I would like to be able to change the approvers field so that the number and order of approvers (users) can be changed dynamically by the user.

What is the best way to do this? I thought I could try and change the approvers field to a JSONField so that users can add / delete / change the order of approvers and then handle the interpretation in the frontend and write some function to interface with django-fsm, but this feels like it conflates things too much. Am I missing a simpler route?

1

There are 1 best solutions below

6
Nimish Bansal On BEST ANSWER

Why not make another model to do so like

class PostApprover(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='approvers')
    user = models.ForeignKey(Approver, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

To access order in which post(let say with id 5) is approved (descending).you can do like

post = Post.objects.get(id=5)
post.approvers.order_by('-created_at')

you can change the value of created_at to change the order. Or you can also make an integer field that determines your order