Fetching inherited model objects in django

后端 未结 4 830
南方客
南方客 2021-01-02 15:50

I have a django application with the following model:

Object A is a simple object extending from Model with a few fields, and let\'s say, a particul

4条回答
  •  天涯浪人
    2021-01-02 16:18

    So long as you order both queries on B and C, it is fairly easy to merge them without having to do an expensive resort:

    # first define a couple of helper functions 
    
    def next_or(iterable, other):
        try:
            return iterable.next(), None
        except StopIteration:
            return None, other
    
    def merge(x,y,func=lambda a,b: a<=b):
        ''' merges a pair of sorted iterables '''
        xs = iter(x)
        ys = iter(y)
        a,r = next_or(xs,ys)
        b,r = next_or(ys,xs)
        while r is None:
            if func(a,b):
                yield a
                a,r = next_or(xs,ys)
            else:
                yield b
                b,r = next_or(ys,xs)
        else:
            if a is not None:
                yield a
            else:
                yield b
        for o in r:
            yield o
    
    # now get your objects & then merge them
    
    b_qs = B.objects.filter(NAME__startswith='Z').order_by('ORDER')
    c_qs = C.objects.filter(NAME__startswith='Z').order_by('ORDER')
    
    for obj in merge(b_qs,c_qs,lambda a,b: a.ORDER <= b.ORDER):
        print repr(obj), obj.__dict__
    

    The advantage of this technique is it works with an abstract base class.

提交回复
热议问题