Question

Im trying to save a list to a manyToManyfield, but I need to use another field beside the ID of the object. I want it to match the list against the field called extid

Here is my models:

class Used_benefit(models.Model):
    name = models.CharField(max_length=255)
    extid = models.PositiveIntegerField(verbose_name="External ID")

    def __unicode__(self):
        return self.name


class UserProfile(AbstractUser):
    benefits = models.ManyToManyField(Used_benefit, blank=True, null=True, related_name="benefits_used")
    updated = models.DateTimeField(blank=True, null=True)    

    objects = UserManager()   

Here is how I try to save the objects:

webuser = UserProfile.objects.get(username__exact=user_id)
productlist = soup.personrecord.productlist.string #The list looks like this: 1,2,6


if productlist:
    webuser.benefits.add(benefits__extid=productlist)


webuser.save() 

But that method does not work. What do I need to do to fix it?

Was it helpful?

Solution

if productlist:
    productlist = productlist.split(",")
    webuser.benefits.add(*Used_benefit.objects.filter(extid__in=productlist))

You don't need webuser.save() unless you're making other changes to webuser object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top