2013-10-15 5 views
0

이 모델 설정에 대한 조언을 찾고 있습니다.Django 모델 - "has_many_through"관계 설정

이 직업 게시판 앱에는 Company, Location, Job이 있습니다.

  • 기업이 작업은 여러 위치를 가질 수 있습니다 작업이 하나의 회사
  • 을 가질 수
  • 회사가 여러 작업
  • 을 가질 수있는 여러 위치를 가질 수 있지만, 각 : 그들은 다음과 같은 관계를 가져야한다 직장의 위치가 유효해야합니다.

이러한 관계가 반영된 모델을 만들고 싶습니다.

class Company(models.Model): 
    name = models.CharField(max_length=200) 
    description = models.TextField() 

class Location(models.Model): 
    is_primary_location = models.BooleanField() 
    address = models.CharField(max_length=200) 
    company = models.ForeignKey(Company) 

class Job(models.Model): 
    title = models.CharField(max_length=200) 
    company = models.ForeignKey(Company) 
    location = models.ForeignKey(Location) 

그러나 정말 "작업 위치 (들)을 가지고 회사를 통해"관계처럼 시행 될 것이다 : 나는 이런 식으로 뭔가가 작동하지 않을 수 있습니다 생각합니다. 모델은 그것을 시행하지 않습니다. 나는 데이터가 표시 될 때 유효한 위치를 필터링해야한다고 생각하며이를 피하고 싶습니다.

대단히 감사합니다.

답변

0

ForeignKey.limit_choices_to을 살펴보십시오.

이렇게하면 사용 가능한 선택 사항을 필터링 할 수 있으며 ModelForm에서 적용됩니다. Job 모델에 이미 회사 외래 키가 있으므로이 키를 사용하여 선택 항목을 필터링 할 수 있어야합니다.

0

나는 https://github.com/digi604/django-smart-selects을 사용하여 끝났으며이 모델을 작성했습니다. `경우 (self.company_id을 : 내가 대신 스마트 선택하여 사용하지 않을 결국

from smart_selects.db_fields import ChainedForeignKey 

class Company(models.Model): 
    name = models.CharField(max_length=200) 
    description = models.TextField() 

class Location(models.Model): 
    is_primary_location = models.BooleanField() 
    address = models.CharField(max_length=200) 
    company = models.ForeignKey(Company) 

class Job(models.Model): 
    title = models.CharField(max_length=200) 
    company = models.ForeignKey(Company) 
    location = ChainedForeignKey(
     Location, 
     chained_field="company", 
     chained_model_field="company", 
     show_all=False, 
     auto_choose=True 
    ) 
+0

그냥 작업이 저장 될 때 유효성 검사 규칙을 추가 (다른 SO 스레드에 따라)이 경우 작품 limit_choices_to 생각하지 않는다! = Location.objects.get (pk = self.location_id) .company_id) : raise ValidationError ('위치가 회사에 유효하지 않습니다')' – billrichards