简体   繁体   中英

django models complex query

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM