问题
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