2017-02-13 2 views
0

기본 클래스에서 일대일 관계를 상속하는 여러 모델이 필요합니다. 내가 템플릿 (또는 뷰 기능)에서 그들을 반복 할 때효과적으로 다중 테이블 상속 사용 (일대일 관계)

지금
from django.db import models 

class Place(models.Model): 
    name = models.CharField(max_length=50) 

class Restaurant(Place): 
    serves_hot_dogs = models.BooleanField(default=False) 
    serves_pizza = models.BooleanField(default=False) 

class Garage(Place): 
    car_brands_serviced = Models.ManyToManyField(Brands) 

class Boutique(Place): 
    for = Models.ChoiceField(choices=(("m", "men"), ("w", "women"), ("k","kids")) 

# etc 

가 어떻게 효과적으로 장소의 다양한 유형을 구분 않습니다 장고의 예에 준하여? 그 템플릿에 번역 얼마나

for place in Place.objects.all(): 
    try: 
     r = place.restaurant 
     # Do restaurant stuff here 
    except ObjectDoesNotExist: 
     try: 
      g = place.garage 
      # Do garage stuff here 
     except ObjectDoesNotExist: 
      try: 
       b = place.boutique 
       # Do boutique stuff here 
      except ObjectDoesNotExist: 
       # Place is not specified 

도 확실하지,하지만이 코드는 매우 잘못하고 비효율적 인 것 같다 지금 (내가 장소를 반복 할 경우 오히려 개별적으로 자식 모델보다) 난 단지이 솔루션을 참조 .

탈출로, 어떤 아동 모델이 관련이 있는지 추적 할 수있는 선택 영역을 만들 수 있지만 위험한 비정규 화와 같습니다.

나는 어떻게 든 이것을 overthinking인가? 어떻게 할 수 있니?

+0

도 확실하지 않음 장소에 place_type' 필드를 더 이상 나쁜 생각입니다. 물론 그것이 비정규 화되지만 장소 유형의 수가 증가하면 많은 조회를 피할 수 있습니다. –

답변

1

그것은 같은 간단한 것일 수 :

models.py :

from django.db import models 

class Place(models.Model): 
    name = models.CharField(max_length=50) 

class Restaurant(Place): 
    serves_hot_dogs = models.BooleanField(default=False) 
    serves_pizza = models.BooleanField(default=False) 
    is_restaurant = True 

class Garage(Place): 
    car_brands_serviced = Models.ManyToManyField(Brands) 
    is_garage = True 

이 템플릿은 다음과 같이 일할 수 - template.html :의`를 추가하는 경우

{% for place in places %} 
{% if place.is_restaurant %} 
    <!-- Restaurant Stuff --> 
{% elif place.is_garage %} 
    <!-- Garage Stuff --> 
{% endif %} 
{% endfor %} 
+0

이것은 아마도 최상의 해결책 일 것입니다. 내가 아는 유일한 다른 옵션은 다음과 같다 :'hasattr (place, "garage")' – themanatuf

+0

이것은 현명한 접근이다. 나는'if' 나'try' 문을 피하기 위해 총알이 없다고 생각합니다. 다음 장소를 반복 할 필요가 없도록 노력하는 것이 가장 좋습니다. 어쩌면 사용자를 즉시 ​​'레스토랑'섹션으로 분기 할 수 있습니다 ... 여기에서 큰소리로 생각해보십시오. –