django data from manytomanyfield intermediate tabl

2019-04-02 17:26发布

Currently, I have the following model structure set up in my models.py (stripped down):

class Admin(models.Model):
    admin_name = models.CharField(unique = True, blank = False, null = False, max_length = 128, verbose_name = u'admin full name')

    def __unicode__(self):
        return self.admin_name
    class Meta:
        ordering = ('id',)
        verbose_name = u'Admin Info'

class Project(models.Model):
    client = models.ForeignKey(Client, verbose_name = u'Client')
    description = models.ForeignKey(Description, verbose_name = u'project description')
    admins = models.ManyToManyField(Admin, verbose_name = u'Administrators', through = 'Admin_Payment')

class Admin_Payment(models.Model):
    admin = models.ForeignKey(Admin, verbose_name = u'Administrator')
    project = models.ForeignKey(Project, verbose_name = u'project')
    agreed_payment = models.DecimalField(max_digits = 16, decimal_places = 2, blank = True, default = 0)

as you can see, I have setup a manytomany relation between my projects and admins using the Admin_Payment as the intermediate table.

My question is how I can make the agreed_payment field (which is in the Admin_Payment class) available to my Project class?

1条回答
家丑人穷心不美
2楼-- · 2019-04-02 18:07

Django creates an attibute admin_payment_set in the Project object that is a "related manager". Access its objects e.g. with "all()". E.g.

p = Project.objects.get(pk=1)
paysets = p.admin_payment_set.all()
paysets[0].agreed_payment
查看更多
登录 后发表回答