简体   繁体   中英

querying parent in model inheritance in django many-to-many by through keyword

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 eg 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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM