【问题标题】:Switch model according to user根据用户切换型号
【发布时间】:2014-12-26 18:26:06
【问题描述】:

在我看来,我需要根据用户切换模型。 我有 2 个想法。

1) 第一个想法

我有一个模型,我称之为 Cakes(maaany 属性)。很抽象。

class Cakes(models.Model):
    radius = models.IntegerField()
    class Meta:
        abstract = True

我把它扩展了 2 次:Vegan Cakes - Non vegan Cakes

class VeganCakes(Cakes):
    class Meta:
        db_table = 'vegancakes'
class NonVeganCakes(Cakes):
    class Meta:
        db_table = 'nonvegancakes'

我的观点是:

from cakes.models import *
# Cakes
# VeganCakes
# NonVeganCakes

标准视图可能是:

class CakesView(DetailView):
    template_name = "desserts/cake_view.html"
    model = Cakes
    context_object_name = 'Cake'
    def get_context_data(self, **kwargs):
        context = super(CakesView, self).get_context_data(**kwargs)
        return context

我想根据用户切换 CakesView 的“模型”字段。

Sasha,属于非素食主义者。 Jessie,属于素食主义者。

所以在视图中,模型变为:Cakes >> VeganCakes/NonVeganCakes

2) 第二个想法 否则我会喜欢在意见之前做:

#if currentUser is Vegan
from cakes.models import Cakes as VeganCakes

#if currentUser is nonVegan
from cakes.models import Cakes as NonVeganCakes

我使用这种方法来分离内容,因为我需要根据用户/组隐藏许多数据。这些数据永远不会一起使用(素食主义者-非素食主义者),也永远不需要交互。

我们仍将非常感谢您提供不同的方法/建议。

非常感谢。

【问题讨论】:

    标签: django authentication django-models django-views


    【解决方案1】:

    您需要覆盖视图的get_queryset 方法。这里是default implementation,这里是docs

    class CakesView(DetailView):
        template_name = "desserts/cake_view.html"
        model = Cakes
        context_object_name = 'Cake'
    
        def get_context_data(self, **kwargs):
            context = super(CakesView, self).get_context_data(**kwargs)
            return context
    
        def get_queryset(self):
            model_class = None
            if is_vegan:
                model_class = VeganCakes
            else:
                model_class = NonVeganCakes
            return model_class.objects.all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多