0

I have 3 tables say, TextObj, User, SecurityCheck. The third table has a Foreign Key attribute (textobj) referencing TextObj and there is a many-to-many field (sharedWith) from SecurityCheck to User.

class SecurityCheck(models.Model):
    textobj=models.ForeignKey(TextObj)
    owner=models.CharField(max_length=255)
    sharedWith=models.ManyToManyField(User)

    def __init__(self,owner,filename,requestingUsername):   
        self.owner=owner
        self.textobj=TextObj.filter(filename=filename)
        self.sharedWith.add(User.objects.filter(username=requestingUsername))

I need to do a query which fetches all the instances of Textobj which have a particular user in the sharedWith field and a particular filename(which is an attribute of TextObj)

3
  • TextObj.objects.filter(securitycheck__sharedWith=user, filename...) Commented Jun 21, 2013 at 10:18
  • are reverse queries allowed in foreign keys? Commented Jun 21, 2013 at 10:20
  • Yes, I've added an answer Commented Jun 21, 2013 at 10:21

1 Answer 1

1

You can easily do queries that span (reverse) relationship:

TextObj.objects.filter(securitycheck__sharedWith=user, filename="foo")

https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

Django offers a powerful and intuitive way to “follow” relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want.

It works backwards, too. To refer to a “reverse” relationship, just use the lowercase name of the model.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.