简体   繁体   中英

Get ManyToMany objects

I'm building a simple application to learn Django.

Basicly a portfolio can have multiple companies in it. I want to display the companies of a certain portfolio of the logged in user.

Models.py

class UserPortfolio(models.Model):
    name = models.CharField(max_length=128, default='X')
    user = models.ForeignKey(User)
    #Company = models.ManyToManyField(Company)

    def __str__(self):
        return self.name

class Company(models.Model):
    name = models.CharField(max_length=128, default='X')
    slug = models.SlugField(max_length=6, default='X', unique=True)

    def get_absolute_url(self):
        return reverse('news:detail',kwargs={'pk': self.pk})

    def __str__(self):
        return self.slug

class PortfolioCompany(models.Model):
    UserPortfolio = models.ForeignKey(UserPortfolio)
    Company = models.ManyToManyField(Company)

views.py

portfolio = UserPortfolio.objects.filter(user=self.request.user)
        myPortfolioRel = PortfolioCompany.objects.filter(UserPortfolio=portfolio)

But now it only displays the ID of the portfolioCompany.

How can I display the Companies inside the UserPortfolio?

Ah found it. I need to work the other way around.

portfolio = UserPortfolio.objects.filter(user=self.request.user)
myPortfolioCompanies = PortfolioCompany.objects.filter(UserPortfolio__in=portfolio)
myCompanies= Company.objects.filter(portfoliocompany__in=myPortfolioCompanies)

Access the many to many field and apply query set filter to it like all or filter or count to use many to many fields.

 company = portfolio.Company.all()

Applying a query set function is required because it's a many to many field and it's required for serialisation of the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM