V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
coolair
V2EX  ›  问与答

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

  •  
  •   coolair · Jun 12, 2018 · 1128 views
    This topic created in 2882 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   ·   2363 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 10:32 · PVG 18:32 · LAX 03:32 · JFK 06:32
    ♥ Do have faith in what you're doing.