代码之家  ›  专栏  ›  技术社区  ›  Bjorn

使用Django模型实现高效多对多扫描的最佳方法是什么?

  •  1
  • Bjorn  · 技术社区  · 16 年前

    我在Django有一个类似的多对多关系:

    class Account ( models.Model ):
      name = models.CharField( max_length = 30 )
      user = models.ForeignKey( User, null = True, blank = True )
    
    class Publisher ( models.Model ):
      publisherID = models.BigIntegerField( )
      name = models.CharField( max_length = 30 )
      lastRequestedId = models.BigIntegerField( )
    
    class Subscription ( models.Model ):
      user = models.ForeignKey( Account )
      twitterPublisher = models.ForeignKey( Publisher )
    

    帐户的发布者列表是订阅列表。每隔一段时间,我都想扫描每个帐户的订阅,查看发布者和更新订阅列表,为帐户订阅中未找到的发布者添加新订阅,并删除帐户发布者列表中未找到的订阅。该列表可从别处获得。

    我得到的出版物列表如下所示:

    [15446531, 15503880, 4909151, 105263800, 21457289, 14293310, 807095, 14511951,
    20032100, 20214495, 15234407, 5988062, 16120265, 50393960, 33933259, 10059852, 652193, 
    88992966, 43166813, 65682198, 14581921, 12044602, 752673, 14414230, 18994120, 17180567, 
    17633960, 1468401, 71876190, 23969777, 63490206, 2425151, 14456474, 18396070, 62205298, 
    11348282, 62581962, 15234886, 30313925, 15166438, 17525171, 15007149, 10760422, 22677790,
    14874480, 22093112, 24741685, 10454572, 19015586, 14572071, 37492156, 6253282, 37996645, 
    18725061, 15983724, 8294212, 24431892, 14589771, 773287, 20772763, 22636391, 816653, 
    19394188, 49793, 1688, 15813140, 20536157, 202003, 685513, 1000591, 17220934, 972651, 
    5668942, 1692901, 15913]
    

    我有一个ID列表 每个帐户

    2 回复  |  直到 16 年前
        1
  •  1
  •   Dmitry Shevchenko    16 年前

    首先,为了方便起见,我将添加一个django的M2M字段 intermediary table 如果没有,则取决于您是否需要订阅的其他数据:

    class Account ( models.Model ):
        name = models.CharField( max_length = 30 )
        user = models.ForeignKey( User, null = True, blank = True )
        publishers = models.ManyToManyField(Publisher, through='Subscription')
    

    然后,您可以使用筛选器排除具有所有发布的帐户

     Account.objects.exclude(publishers__publisherID__in=[1,2])
    

    最后,您所要做的就是将新的发布者附加到已过滤的帐户。

        2
  •  0
  •   Community Mohan Dere    9 年前

    dmishe给了我正确的方向,但也许我需要做的是在这个答案中所做的:

    Querying django ManyToMany

    Publication.objects.filter(subscription__group=account_instance)
    

    大概