Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django bulk remove and add many to many relationships

Im having a problem with bulk many to many relationship removing and adding.

This is the JS that sends the pk of the user to be updated and the pk of the skills that will be added to the many to many.

function attachskillls(){

var checkedValues = $('input:checkbox:checked').map(function() {
  return this.value;
}).get();

console.log(checkedValues)

data = {
  'skills' : checkedValues,
  'pk' : getUrlVars()["id"]
}
console.log(data)

$.ajax({
  type: "POST",
  url: "/api/skill/attch/",
  data: JSON.stringify(data),
  contentType: "application/json",
  dataType: "json"
})

data is packed like this

{"skills":["1","2","3"],"pk":"1"}

This is the model the skills will be related to

class Resource(models.Model):

    title = models.CharField(max_length=10)
    preferred_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=30)
    employstatus = models.CharField(max_length=20)
    employer = models.ForeignKey('Employer')
    role = models.ForeignKey('Role')
    location = models.ForeignKey('Location')
    workphone = models.CharField(max_length=25, blank=True, null=True)
    mobile_phone = models.CharField(max_length=15, blank=True, null=True)
    email = models.CharField(max_length=15, blank=True, null=True)
    notes = models.CharField(max_length=200, blank=True, null=True)
    updated_by = models.CharField(max_length=30, blank=True, null=True)
    skillset = models.ManyToManyField('ReferenceSkillList')

This is my api so far I am trying to filter resource by pk so I have the correct user to add the skills to then to clear all relationships that may already be added then to bulk add the new relationships.

def Skillattachment(request):
    body = json.loads(request.body)
    if request.method == "POST":
        pk = body['pk']
        skills = body
        res = Resource.objects.filter(pk=pk)
        res.skillset.clear()
        res.skillset.add(skills)

    else:
        search_id = ''

    return HttpResponse(json.dumps(body), content_type='application/json')

Is there a better way to do what I am trying todo?

I I currently get the error 'QuerySet' object has no attribute 'skillset' though I am unsure why? maybe I have made the M2M incorrectly but I have followed the docs

like image 379
SpeedyH30 Avatar asked Jan 26 '26 00:01

SpeedyH30


1 Answers

You should use res = Resource.objects.get(pk=pk) instead. filter would give you a queryset as result.

Also your variable skills is just a data structure not objects. You might need:

skills = ReferenceSkillList.objects.filter(id__in=body['skills'])
res = Resource.objects.get(pk=pk)
res.skillset.clear()
res.skillset.add(*skills)

Django docs.

like image 98
Shang Wang Avatar answered Jan 27 '26 15:01

Shang Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!