django data from manytomanyfield intermediate table

安稳与你 提交于 2019-12-05 06:42:36

问题


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:


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


来源:https://stackoverflow.com/questions/4618295/django-data-from-manytomanyfield-intermediate-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!