Bokeh & Django: RuntimeError("Модели должны принадлежать только одному документу")

Я делаю несколько графиков боке, используя python bokeh и django. Я пытаюсь выстроить эти графики в ряд, но это не удается на строке:

script, div = components(row(sample_plot, variant_plot, sizing_mode='scale_width'))

в приведенном ниже коде. Если я пытаюсь отобразить один график, созданный с помощью этого метода, он работает. Сообщение об ошибке, которое я получаю, следующее:

Я очень озадачен, почему это происходит, когда я размещаю свои участки в ряд.

ERROR (exception.py:118; 04-11-2021 16:56:58): Internal Server Error: /
Traceback (most recent call last):
  File "/home/hts_django/config/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/home/hts_django/config/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/hts_django/config/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/hts_django/config/env/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/hts_django/config/env/lib/python3.6/site-packages/django/views/generic/base.py", line 89, in dispatch
    return handler(request, *args, **kwargs)
  File "/path/2/ma/viewz/HTS/views.py", line 932, in get
    script, div = components(plot_row)
  File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/embed/standalone.py", line 216, in components
    with OutputDocumentFor(models, apply_theme=theme):
  File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__
    return next(self.gen)
  File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/embed/util.py", line 134, in OutputDocumentFor
    doc.add_root(model)
  File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/document/document.py", line 321, in add_root
    self._pop_all_models_freeze()
  File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/document/document.py", line 1104, in _pop_all_models_freeze
    self._recompute_all_models()
  File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/document/document.py", line 1127, in _recompute_all_models
    a._attach_document(self)
  File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/model.py", line 692, in _attach_document
    raise RuntimeError("Models must be owned by only a single document, %r is already in a doc" % (self))
RuntimeError: Models must be owned by only a single document, Figure(id='1080', ...) is already in a doc

Виды (с примером функции для построения графика)

def create_variant_barchart():
    """ Create a sample tracking barchart for all sites.
        args: None
        returns: plot
    """

    crs_qs = ClinicallyReportedSample.objects.filter(
        second_interpret=False,
        final_technical_report=True,
        reported_on_panel__parent_panel__isnull=False,
        diagnostic_report_required=True)

    first_analysis = crs_qs.filter(
        final_technical_check=True,
        first_report=False)

    crv_qs = ClinicallyReportedVariant.objects.filter(
        clinically_reported_sample_id__in=first_analysis,
        technical_status='valid')

    num_variants = [o.final_vasr_id.variant_annotation_id.\
        variant_gene_transcript_id.variant_id.id for o in crv_qs]
    unique_variants = list(set(num_variants))

    classified_variants = VariantClassification.objects.filter(
        variant_annotation_id__variant_gene_transcript_id__variant_id__in=unique_variants,
        reviewed_by=True)

    to_classify_variants = len(unique_variants) - len(classified_variants)

    x_axis = ['Samples', 'Variants']
    counts = [len(first_analysis), to_classify_variants]

    p = figure(
        title="Unclassified Variants",
        x_range=x_axis,
        height=350,
        toolbar_location=None,
        tools="hover",
        tooltips="@counts"
    )

    # p.vbar(x=x_axis, top=counts, width=0.9)
    source = ColumnDataSource(data=dict(index=x_axis, counts=counts, color=Spectral6))
    p.vbar(x='index',
        top='counts',
        width=0.9,
        color='color',
        source=source
    )

    p.y_range.start = 0

    return p

 class DashoardView(View):

    def get(self, request, *args, **kwargs):

        sample_plot = create_barchart_all_sites()
        variant_plot = create_variant_barchart()

        script, div = components(row(sample_plot, variant_plot, sizing_mode='scale_width'))

        self.context['script'] = script
        self.context['div'] = div

        return render(request, self.template, self.context)

шаблон

<div class="row">
  <div class="col mb-3">
      <div id='outstanding_samples' class='card'>
        <div class="card-header bg-light">
          <h6><b>HODB Overview</b></h6>
        </div>

        <div class='container-fluid card-body'>
            {{div|safe}}
            {{script|safe}}
        </div>

    </div>
  </div>
</div>

Я изменил имена переменных в обеих приведенных ниже функциях, поскольку они обе сохранили свои соответствующие графики как p .... bokeh не любит, когда они одинаковые!

    sample_plot = create_barchart_all_sites()
    variant_plot = create_variant_barchart()
Вернуться на верх