[Answered ]-Django Find custom user with the same value of JSONfield

1๐Ÿ‘

โœ…

I would advise not to work with a JsonField to refer to other models. SQL databases often are not good with recursive and dynamic data, since that is not how a relational database conceptually is designed.

Typically a ManyToManyField [Django-doc] is used. This will work with a junction table [wiki], which makes it more accessible and it can guarantee referential integrity.

We thus can model this with:

class ProgrammingLanguage(models.Model):
    name = models.CharField(unique=True)

class User(models.Model):
    languages = models.ManyToManyField(
        ProgrammingLanguage,
        related_name='users'
    )

If we then have a User object user, we can find users which have at least one language in common with:

User.objects.filter(
    languages__users=user
).distinct()

The .distinct() call [Django-doc] will avoid retrieving the same user that many times as they have languages in common.

Leave a comment