Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

python - Not able to get list of ManytoMany field using filter

views

create = Create.objects.filter(campaign_id=campaign_id).values()
print (create)
saved = create.produces.filter(active=True).values()
print(saved)

models

class Create(models.Model):
user = models.ForeignKey(User,on_delete= models.CASCADE,blank=True)
campaign = models.ForeignKey(Campaign,on_delete=models.CASCADE,blank=True)
produces = models.ManyToManyField(Saved,blank=True)



class Saved(models.Model): 
user = models.ForeignKey(User,on_delete= models.CASCADE,blank=True)
unique_key = models.CharField(max_length=2000,default='')
text = models.CharField(max_length=2000,default='')
active = models.BooleanField(default=False,blank=True)

How to get all saved with active=True

It is giving error of saved = create.produces.filter(active=True).values() AttributeError: 'QuerySet' object has no attribute 'produces'

in the output of print(create) their is no produce field


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here create is a queryset , it's like a list When you have a list of numbers say :

list = [1,2,3]

you cant run number methods on that list object So what you should do is :

all_objs = {}
for obj in create:
    objs = obj.produces.filter(active=True).values()
    all_objs.update(objs)

print(all_objs)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...