filter on multiple tables

202 views
Skip to first unread message

Soumen Khatua

unread,
May 28, 2020, 4:27:58 PM5/28/20
to django...@googlegroups.com
Actually I want to filter all users those are matched with currently logged in users based on location or education details like maybe institute_name or specialization. Is it possible to search in multiple tables?!
I almost spent 2 days but still I stuck in the position.
Any help would be appreciated.

Thank You

Regards,
Soumen


class Location(models.Model):
    name = models.CharField(max_length = 15)

class Profile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete = models.CASCADE,
        related_name="profile"
    )
    location = models.ManyToManyField(Location,related_name = 'user_locations')

class Education(models.Model):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE,related_name="profiles")
    institute_name = models.CharField(max_length = 250)
    specialization = models.CharField(max_length = 100)


אורי

unread,
May 29, 2020, 12:27:21 AM5/29/20
to django...@googlegroups.com
Hi Soumen,

You can filter on another table by using <table_name>__<field>, for example:

User.objects.filter(profile__profiles__institute_name="Example")

Or:

User.objects.filter(profile__profiles__institute_name__in=["Example 1", "Example 2"])


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAPUw6WZqX9oqutYfGJqAwCswY_00VfTmf624ypypAr6saS61Nw%40mail.gmail.com.

Soumen Khatua

unread,
May 29, 2020, 10:36:02 AM5/29/20
to django...@googlegroups.com
Hi,

whenever I'm trying to filter as per your convention I'm getting some error like FieldError:
Eg. profile = Profile.objects.filter(education__profile__institute_name="IIT KGP")

of course, I'm getting this error because Profile is working here as a Foreign Key, in Education table.

actually I want to fetch all the users those are from the same Institution or Specialization or location.


Thank you for your response and time.

Regards,
Soumen


Soumen Khatua

unread,
May 29, 2020, 10:49:27 AM5/29/20
to django...@googlegroups.com
Thank You, for your guidance.I think I'm very close to this problem.

Thank you once again.

‪On Fri, May 29, 2020 at 9:56 AM ‫אורי‬‎ <u...@speedy.net> wrote:‬
Reply all
Reply to author
Forward
0 new messages