【问题标题】:What is the best means to achieve efficient many-to-many scanning with Django models?使用 Django 模型实现高效多对多扫描的最佳方法是什么?
【发布时间】:2011-01-09 09:43:34
【问题描述】:

我在 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 )

帐户的发布者ID 列表是订阅列表。每隔一段时间,我想使用这样的发布者ID 列表扫描每个帐户的订阅并更新订阅,为帐户订阅中未找到的发布者ID 添加新订阅,并删除帐户发布者ID 列表中未找到的订阅。此列表在别处获得。

最好的方法是什么? Subscription.objects.all(),然后遍历每个(可能很多!)并跟踪订阅和用户,一旦我了解数据库的当前状态与新信息,最终更新?或者我是否循环访问帐户并在 Subscription 对象上使用 filter()?这会导致很多mysql查询吗?

我得到的 publisherID 列表如下所示:

[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 列表。如果用户的订阅不在该用户的发布者 ID 列表中,我还想删除订阅。

【问题讨论】:

  • 如果能就这个问题获得一些意见会很棒。这个问题有什么问题吗?

标签: django django-models loops many-to-many manytomanyfield


【解决方案1】:

首先,为方便起见,我会在 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')

然后您可以使用过滤器排除具有所有发布者ID的帐户

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

最后,您只需将新发布者附加到过滤后的帐户即可。

【讨论】:

  • 好吧,如果不够具体,我很抱歉,但我有每个帐户的 ID 列表。如果用户的订阅不在该用户的发布者 ID 列表中,我也想删除订阅。
【解决方案2】:

dmish 让我朝着正确的方向前进,但也许我需要做的是这个答案中正在做的事情:

Querying django ManyToMany

Publication.objects.filter(subscription__group=account_instance)

也许?

【讨论】:

    猜你喜欢
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2018-01-04
    • 2012-04-25
    • 2010-12-02
    • 2020-06-08
    相关资源
    最近更新 更多