Nie Selam
Nie Selam

Reputation: 1451

ORM or RAW SQL that shows if a parent data is in use in child tables

Sorry for the confusing title. If someone can suggest, please do.

I have this 4 models:

  Parent()

  Child():
    parent= models.ForeignKey(Parent,related_name='parent_child')

  Member()

  MemberChild():
    member= models.ForeignKey(Member, related_name='member_child')
    child = models.ForeignKey(Child, related_name='child_member')

Now, what I want is to list all parents and see if they are in use by the logged in member. Given the data below, how can I get list of all parents while adding a flag/boolean field to indicate if the member is associated with any child of the parent? What is the DJANGO ORM or even RAW SQL that would give the output below the sample data.

Sample Data:

     Parent
      1           Parent1
      2           Parent2

     Child
      1     1     Child1

     Member
     1          Member1

     MemberChild
     id   child   member
     1      1      1

Now the expected output is (for member id 1):

     Parent1 True
     Parent2 False

in which True means any Child of parent1 is currently being used by the member.

Upvotes: 0

Views: 51

Answers (1)

Ngoc Pham
Ngoc Pham

Reputation: 1458

you can try like this :

Parent.objects.annotate(
    parent_logged_member=Case(
        When(parent_child__child_member__member_id__isnull=False, then=True),
        default=False,
        output_field=BooleanField(),
    )
)

Parent in list have field annotate parent_logged_member. True if used by member.

Upvotes: 1

Related Questions