django模型的假反向关系

时间:2014-09-02 14:51:07

标签: django orm reverse foreign-key-relationship

我有以下代码:

class Transaction(models.Model):
    pass

class Shipment(models.Model):
    tx = models.ForeignKey(Transaction)
    sub = models.ForeignKey(Subscription)


class Subscription(models.Model):
    pass

我尝试在Subscription和Transaction之间建立反向关系,如下所示:

subscription.transaction_set.all()

我能想到的唯一方法是使用这样的虚假财产:

class Subscription(models.Model):

    @property
    def transaction_set(self):
        return Transaction.objects.filter(
            pk__in=[s.tx.pk for s in self.shipment_set.all()]
        )

但现在我遇到了管理问题。我想在管理站点中使用admin.TabularInline列出交易。这是我的解决方案崩溃的地方。有没有人有任何想法?

我还需要使用admin.TabularInline列出货件。

1 个答案:

答案 0 :(得分:3)

您正在查看through形式:

class Transaction(models.Model):
    pass

class Subscription(models.Model):
    transactions = models.ManyToManyField(Transaction, through='Shipment')

class Shipment(models.Model):
    tx = models.ForeignKey(Transaction)
    sub = models.ForeignKey(Subscription)

然后:

subscription.transactions.all()