Reputation: 2416
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?
Upvotes: 1
Views: 1128
Reputation: 2897
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.
Upvotes: 1