我有以下问题:
我的模型设置与以下场景类似
class Membership(models.Model):
user = models.ForeignKey(User)
verified = models.BooleanField()
class ClubMembership(Membership):
club = models.ForeignKey(Club)
class ForumMembership(Membership):
forum = models.ForeignKey(Forum)
class Club(models.Model):
members = models.ManyToManyField(User, through='ClubMembership')
class Forum(models.Model):
members = models.ManyToManyField(User, through='ForumMembership')
(我曾经将Membership作为抽象类,但这不会让我查询基类。)我现在想查询例如所有尚未针对特定用户进行验证的成员资格。我能做到
memberships = Membership.objects.filter(verified=False)
这给了我一个名为Verified = False的所有成员资格的列表。然而,我无法找到任何方法1)检查成员资格的子类和2)我无法访问“俱乐部”或“论坛”字段,即使我知道子类型。在我查询基类后,无论如何都要访问基类类型,我如何访问子类字段?
答案 0 :(得分:3)
1)检查成员资格的哪个子类
您可以通过检查属性
来实现if hasattr(membershipobj, 'clubmembership'):
#its base for ClubMembership
elif hasattr(membershipobj, 'forummembership'):
#its for ForumMembership
2)我无法访问“俱乐部”或“论坛”字段
通过子对象访问子对象字段
membershipobj.clubmembership.club
membershipobj.forummembership.forum