过滤具有2级反向关系的urlencode

Filter urlencode with 2 Level reverse relationship

我有这些 models:

class Issuer(models.Model):
    name = models.CharField()

    @property
    def investor_count(self):
        return Investment.objects.filter(offering__issuer_id=self.pk).count() or 0

    def __str__(self):
        return self.name

class Offering(models.Model):
    issuer = models.ForeignKey(Issuer, on_delete=models.CASCADE)
    name = models.CharField()

    def __str__(self):
        return self.name

class Investment(models.Model):
    offering = models.ForeignKey(Offering, on_delete=models.CASCADE)
    name = models.CharField()

    def __str__(self):
        return self.name

我想在 Issuer 列表视图中显示它拥有的投资数量。这是我目前使用的功能,

# link investments to page
def view_investments_link(self, obj):
    count = obj.investor_count
    url = (
        reverse("admin:crowdfunding_investment_changelist")
        + "?"
        + urlencode({"issuer__id": f"{obj.id}"})
    )
    return format_html('<a href="{}">{} Investment(s)</a>', url, count)

view_investments_link.short_description = "NUMBER OF INVESTMENTS"

这是它的样子:

但是行+ urlencode({"issuer__id": f"{obj.id}"})不起作用。它将我的 url 更改为 http://localhost:8000/app/investment/?e=1。有没有办法使用 issuer_id 过滤 Investments?

如果您想按 issuer_id 过滤 投资,您只需更改 list_filter 在 ModelAdmin 中像这样

@admin.register(Investment)
class Investment_Register(admin.ModelAdmin):
    list_filter = ["offering__issuer__id"]

然后像这样将issuer的id传给URL http://localhost:8000/app/investment/?offering__issuer__id={id-issuer}

注意:如果你给出这样的错误

(admin.E116) The value of 'list_filter[0]' refers to 'offering__issuer__id', which does not refer to a Field.

将字段 ID 最少添加到您的模型