문제

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  
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top