开发者

Many-to-many "by proxy" relathionship in django

My data model consists of three ma开发者_开发技巧in entities:

class User(models.Model):
    ...

class Source(models.Model):
    user = models.ForeignKey(User, related_name='iuser')
    country = models.ForeignKey(Country, on_delete=models.DO_NOTHING)
    description = models.CharField(max_length=100)

class Destination(models.Model):
    user = models.ForeignKey(User, related_name='wuser')
    country = models.ForeignKey(Country)

I am trying to create a queryset which is join all sources with destinations by user (many to many). In such a way I would have a table with all possible source/destination combinations for every user. In SQL I would simple JOIN the three tables and select the appropriate information from each table.

My question is how to perform the query? How to access the query data?


In django queries are done on the model object, its well documented. The queries or querysets are lazy and when they execute they generally return a list of dict, each dict in the list contains the field followed by the value eg: [{'user':'albert','country':'US and A :) ','description':'my description'},....].

All possible source,destination combinations for every user?

I think you will have to use a reverse relation ship to get this done eg:

my_joined_query = User.objects.values('user','source__country','source__description','destination__country')

notice that i'm using the smaller case name of the models Source and Destination which have ForeignKey relationship with User this will join all the three tabels go through the documentation its rich.

Edit:

To make an inner join you will have to tell the query, this can be simply achieved by using __isnull=False on the reverse model name:

my_innerjoined_query = User.objects.filter(source__isnull=False,destination__isnull=False)

This should do a inner join on all the tables.

Then you can select what you want to display by using values as earlier.

hope that helps. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜