Home > Back-end >  How can I add ordering for ManyToMany field?
How can I add ordering for ManyToMany field?

Time:05-16

I have two models: CustomUser and AgreementReglament At this moment relation between the models looks like this:

class AgreementReglament(models.Model):
    name = models.CharField(max_length=32) # just name of the reglament
    approvers = models.ManyToManyField( # set of users to approve
        'CustomUser',
        related_name='agreement_reglaments'
    )

How can I set order of approvers (e.g. CustomUser1 should be the first in particular AgreementReglament1, CustomUser2 should be second and so on, but in AgreementReglament2 CustomUser2 can be the first)

UPDATE: ordering is based on the POST request data Example of post request to create AgreementReglament:

{
        "name": "Reglament1",
        "approvers": [
             {
                  "approver_name": "Alex",
                  "approver_order": 1,
             },
             {
                  "approver_name": "Bob",
                  "approver_order": 2,
             }
        ]
    }

CodePudding user response:

If you mean the approver order value will be entered as a field , then I would create a model lets say For example Approvals and it will have a FK field for User and a FK field for Agreement , and a third field for the approver_order. And leave the Agreement Model to have only name field. But , If you mean to sort based on a condition , the question needs more details to be clarified as (what the ordering is based on ? What is the field you’re ordering exactly ?)

UPDATE: After seeing your update what I understood is that you get this ordering from the POST request data and for the example you provided, you definitely need a field to store the order for each User. I suggest going with the same answer, create a model in the middle and link both models with that Model using the through attribute and that might look like this:

class Approval(models.Modal):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    agreement = models.ForeignKey(AgreementReglament, ...)
    order = models.#whatever you want this char or int

and in one of the other models (doesn't really matter) they should be like this:

class AgreementReglament(models.Model):
    name = models.CharField(max_length=32) # just name of the reglament
    approvers = models.ManyToManyField( # set of users to approve
        'CustomUser',
        related_name='agreement_reglaments', through='Approval'
    )

If you have any questions, feel free to ask.

  • Related