I have the following problem:
My models are set up similarly to the following scenario
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')
(I used to have Membership as an abstract class but this wouldn't let me query the base class.) I now want to query e.g. all memberships that have not yet been verified for a specific user. I can do
memberships = Membership.objects.filter(verified=False)
and this gives me a list of all memberships with verified=False. I can't however find any way to 1) check which subclass the membership is and 2) I can't access the 'club' or 'forum' field, even when I know the subclass type. Is there anyway to access the base class type after I've queried the base class, and how do I access the subclass fields?
1) check which subclass the membership is
You can do that by checking the attribute
if hasattr(membershipobj, 'clubmembership'):
#its base for ClubMembership
elif hasattr(membershipobj, 'forummembership'):
#its for ForumMembership
2) I can't access the 'club' or 'forum' field
Access child objects fields, through child object
membershipobj.clubmembership.club
membershipobj.forummembership.forum