Найти - Пользователи
Полная версия: DRY views
Начало » Django » DRY views
1 2
infoforfoi
Подскажите, пожалуйста, саму логику, как избежать нарушения DRY Django, помогите упростить код
def prodazha_x(request):
    estate = Estates.objects.select_related().filter(show=True).order_by('type_estate','cost_value','cost')
    type_all = Type_estates.objects.select_related().all().order_by('title')
    type_have = type_all.filter(estates__isnull=False).values('title', 'slug_title').distinct()
    type_com = type_have.filter(estates__business=True)
    return render_to_response('estates/estates.html',
    {   
        'real': estate,
        'real_com' : estate.filter(business=True),
        'type_all' : type_all,
        'type_have' : type_have,
        'type_com' : type_com, 
        'type_other': type_have.exclude(id__in=[1,2,]),
        'count_flat': estate.filter(type_estate=1).count(),
        'count_home': estate.filter(type_estate=2 ).count(),
        'count_com': estate.filter(business=True).count(),
        'count_new': estate.filter(new=True).count(),
        'count_other': estate.exclude(type_estate__id__in=[1,2,]).count(),        
    }, context_instance = RequestContext(request) )
def kuplyu_x(request):
    buy = Buy.objects.select_related().filter(show=True).order_by('type_estate','cost_value','cost')
    type_all = Type_estates.objects.select_related().all().order_by('title')
    type_have = type_all.filter(buy__isnull=False).values('title', 'slug_title').distinct()
    type_com = type_have.filter(buy__business=True)    
    return render_to_response('estates/estates.html',
    {   
        'real': buy,
        'real_com' : buy.filter(business=True),
        'type_all' : type_all,
        'type_have' : type_have,
        'type_com' : type_com, 
        'type_other': type_have.exclude(id__in=[1,2,]),
        'count_flat': buy.filter(type_estate=1).count(),
        'count_home': buy.filter(type_estate=2 ).count(),
        'count_com': buy.filter(business=True).count(),
        'count_new': buy.filter(new=True).count(),
        'count_other': buy.exclude(type_estate__id__in=[1,2,]).count(),   
    }, context_instance = RequestContext(request) ) 
в шаблонах типа {{ real }}, урлы типа /estate/prodazha/ и /estate/kuplyu/ Может можно и урлы объединить

вынести хотя бы часть, в контекст не всего проекта, а только приложения
FishHook
CBV, CBV это радость для нас,
Классы и наследованье тоже,
CBV, CBV, начинаем рассказ
Тут все тынцы по порядку сложены
infoforfoi
это наверное классно, но я еще в начале многого не понимаю, может попроще, что-то есть
FishHook
def common_view(request, model):
    item = model.objects.select_related().filter(show=True).order_by('type_estate','cost_value','cost')
    type_all = Type_estates.objects.select_related().all().order_by('title')
    param_name=model.__name__.lower()
    type_have = type_all.filter(**{param_name + "__isnull": False}).values('title', 'slug_title').distinct()
    type_com = type_have.filter(**{param_name + "__business": True})
    return render_to_response('estates/estates.html',
                              {
                                  'real': item,
                                  'real_com' : item.filter(business=True),
                                  'type_all' : type_all,
                                  'type_have' : type_have,
                                  'type_com' : type_com,
                                  'type_other': type_have.exclude(id__in=[1,2,]),
                                  'count_flat': item.filter(type_estate=1).count(),
                                  'count_home': item.filter(type_estate=2 ).count(),
                                  'count_com': item.filter(business=True).count(),
                                  'count_new': item.filter(new=True).count(),
                                  'count_other': item.exclude(type_estate__id__in=[1,2,]).count(),
                                  }, context_instance = RequestContext(request) )
infoforfoi
спасибо, за такой подробный ответ… Но подскажи, пожалуйста, еще немного
item = model.objects… model - как он тут определяет какую из 4 моделей взять…
Или тут просто нужно подставить определенную модель… но тогда опять теряется чистота кода, и каждую строку нужно умножить на 4… Вернее теперь почти каждую
FishHook
Если Вы внимательно посмотрите в мой код, то увидите, что вторым параметром в функцию передается модель. Как это использовать зависит от Ваших предпочтений и фантазии, вариантов тут много, например так
def common_view(request, model):
    """ см. выше """
def prodazha_x(request):
    return common_view(request, Estates)
def kuplyu_x(request):
    return common_view(request, Buy)
или заюзать partial, или передавать имя модели в урле или …
В общем научитесь уже обращаться с языком на котором пишете.
infoforfoi
разобрался, спасибо еще раз!
infoforfoi
здесь же по теме, как определить, что находишься от вьюхи common_view в шаблоне

{% if url common_view %} т.е. Что-то, если мы находимся от вьюх: prodazha_x, kuplyu_x и т.д.
{% elif url common_view2 %} здесь по тому же принципу, другое
{% endif %}
FishHook
{{ request.path }}
{{ request.get_full_path }}
infoforfoi
делал, так:
{% if request.get_full_path = '/nedvizhimost/prodazha/' or request.get_full_path = '/nedvizhimost/kuplyu/' %} 
так работает, а возможно как-то это сократить?
типа {% if request.get_full_path = common_view %}

или может как-то все-таки возможно передать переменную, Prodazha, kuplyu и т.д.
Внутри шаблонного тега? к сожалению сам не смог найти простого решения
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB