如何过滤嵌套的相关 django 对象

Dom*_*och 7 django django-models django-rest-framework

我有一个应用程序,其中有很多投资者投资相同的轮次,这些轮次都属于公司,如下所示。但是,当用户(投资者)登录时,我只希望他能够看到他的投资。

    {
        "id": 1,
        "name": "Technology Company",
        "rounds": [
            {
                "id": 1,
                "kind": "priced round",
                "company": 1,
                "investments": [
                    {
                        "id": 1,
                        "investor": 1,
                        "round": 1,
                        "size": 118000,
                    },
                    {
                        "id": 2,
                        "investor": 2,
                        "round": 1,
                        "size": 183000,
                    },
                ]
            }
        ]
    },
Run Code Online (Sandbox Code Playgroud)

目前,我的视图集扩展get_queryset如下:

class CompanyViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        user = self.request.user
        investor = Investor.objects.get(user=user)
        companies = Company.objects.filter(rounds__investments__investor=investor)
        return companies
Run Code Online (Sandbox Code Playgroud)

它检索属于投资者的投资,但是当它再次使用这些投资来检索轮次时,它会与所有投资者一起抢占该轮次。

我怎么写才能让它只向投资者显示下面的投资?

这是我的模型:

class Company(models.Model):
    name = models.CharField(max_length=100)

class Round(PolymorphicModel):
    company = models.ForeignKey(Company, related_name='rounds', blank=True, null=True)

class Investment(PolymorphicModel):
    investor = models.ForeignKey(Investor, related_name='investor')
    size = models.BigIntegerField(default=0)
Run Code Online (Sandbox Code Playgroud)

Tom*_*lch 7

Your description of what happens is pretty unclear. What does "when it takes those investments again" mean? Anyway, I'm guessing what you need to do is to use .prefetch_related and a Prefetch object.

from django.db.models import Prefetch

class CompanyViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        user = self.request.user
        investor = Investor.objects.get(user=user)
        companies = Company.objects.filter(
            rounds__investments__investor_id=investor.id
        ).prefetch_related(Prefetch(
            'rounds__investments',
            queryset=Investment.objects.filter(
                investor_id=investor.pk,
            ),
        ))
        return companies
Run Code Online (Sandbox Code Playgroud)

I haven't tested this snippet but it should give you a pointer in the right direction. I also optimized the investor lookup to check the id only, this will save you an unnecessary indirection.