在Django Admin中显示超链接反向外键

时间:2016-06-01 14:04:21

标签: django django-admin

我有两个型号

class Transaction(TimeStampedModel):
    """
    Stores transaction details
    """
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    payment_method = models.CharField(max_length=40)

class OrderDetail(TimeStampedModel):
    """
    Model to store the order details at time of payment
    """
    transaction = models.ForeignKey(payment_models.Transaction, null=True, blank=True)
    order_amount = models.FloatField()

两个OrderDetails可能有相同的事务链接。我希望在我的交易详细信息管理中链接到链接到该交易的所有订单。我该怎么做?

1 个答案:

答案 0 :(得分:2)

你可以试试这个

class TransactionAdmin(admin.ModelAdmin):
    readonly_fields = ('order_details')

    def form_url(self, id):
        url = reverse("admin:reverse_url", args=[id])
        return '<a href=%s>%s</a>'%(url, id)

    def order_details(self, obj):

        return "<br>".join([self.form_url(k.id) for k in obj.orderdetail_set.all()])

    order_details.allow_tags=True
    form_url.allow_tags=True