Home > Mobile >  How to update M2M field related data attributes in Django
How to update M2M field related data attributes in Django

Time:07-15

enter image description hereI want to update the vote value of each candidate which is related with m2m field of specific Constituencies. I have Constituencies update function where user update the Constituencies but i my case i also want to update the candidates vote value which is coming from object in object.candidates.all


class Candidates(models.Model):

    name = models.CharField(max_length=100)
    votes = models.PositiveBigIntegerField(default=0)

class Constituencies(models.Model):
    candidates = models.ManyToManyField(Candidates)

views.py

def constituency_detail(request, pk):
    obj = get_object_or_404(Constituencies, id=pk)
    form = ConstituenciesForm(request.POST or None, instance=obj)

    if request.method == 'POST':
        pass

template.html

<h5>{{ object }}</h5>

{% for object in object.candidates.all %}
<h5>{{ object }}</h5>
{{ object.votes }} as input field  
{% endfor %}

this is a concept

CodePudding user response:

You can use the Django ORM update() function with an F() object:

Candidate.objects.filter(...).update(votes=F('votes') 1)

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.update

Edit:

Your votes are an Integer field, presumably votes are being cast somehow - a better method would be to have a Vote model that tracks other information - you can then use the ORM to count the number of Votes attached to each Candidate

CodePudding user response:

Whenever you have <model name>.objects.all(), you get a query set a response.

In your case, if you want to increase the count of each object, you can simply loop over all those objects.

An example would be:

# this will return a list of objects which is QuerySet
candidates = Candidates.objects.filter("apply your filter here")

for candidate in candidates:
    candidate.vote  = 1
    candidate.save()
  • Related