coolair
V2EX  ›  问与答

请教一下 Django 如何使用 Many To Many 的属性过滤

  •  
  •   coolair · Jun 12, 2018 · 1158 views
    This topic created in 2893 days ago, the information mentioned may be changed or developed.
    class Parent(models.Model):
        items = models.ManyToManyField(Item, verbose_name='子项')
    
    class Item(models.Model):
        sn = models.CharField('序列号', max_length=20)
    

    现在想得到所有 items 都小于某个值 value 的 parent: Parent.objects.filter(items__sn__lt=value).all() 这样写不对,只要有一个 item 小于 value 就会出来,而且会重复出现几次,正确的写法是怎样的呢?

    2 replies    2018-06-12 12:01:47 +08:00
    SingeeKing
        1
    SingeeKing  
    PRO
       Jun 12, 2018
    p = []
    items = Item.objects.filter(sn__lt=value)
    for item in items:
    p.append(item.parent)
    coolair
        2
    coolair  
    OP
       Jun 12, 2018
    @SingeeKing 这样不对吧,不是所有 items 都小于了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3725 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 00:43 · PVG 08:43 · LAX 17:43 · JFK 20:43
    ♥ Do have faith in what you're doing.