Music Cause
Music Cause

Reputation: 173

Query data in django matched with ids in a list

I am trying to update some data in my django models But kinds stuck on how to get that particular attributes. see I have a list name ids = ['112', '111', '114', '113', '115'] And I have a model name Member

class Member(models.Model ):
    user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE)
    com = models.ForeignKey(Committee, on_delete=models.CASCADE,verbose_name='Committee Name')
    mem_status = models.CharField( max_length=20,choices=MEMBER_STATUS, verbose_name='Member Status')
    mem_note = models.TextField(null=True, blank=True)
    mem_order = models.IntegerField(default=0)

So each id in ids have a object available in Member Model, What I want is to update the mem_order of each object like this. suppose 111 in ids is at 2nd index. I want to set mem id with 111 to set 2 in mem_order. I am getting all the desired members from Member table Now I dont know how to loop over those ids and match them the id of Each Member from Member model.

Upvotes: 1

Views: 422

Answers (1)

raphael
raphael

Reputation: 2880

This is perhaps not very efficient, but I think it will work.

for index, id in enumerate(ids, start=1):
    member = Member.objects.get(pk=id)
    member.mem_order = index
    member.save()

Using python's enumerate function you can iterate through the index and values of the ids list, then fetch the member with the id value in that list. Then set the mem_order to the index, and finally save it. The enumerate has start=1 so the first item in the list, '112' will have the index of 1, and the value of '112'.

Upvotes: 1

Related Questions