2014-03-31 2 views
1

Django를 처음 사용하므로 올바른 방향으로 가고 있지 않다면 알려주십시오. 저는 장고 프로젝트를 만들고 있는데 한 모델에서 데이터를 검색하여 다른 모델에서 사용하는 올바른 장고 방법을 묻고 싶습니다.Django - 외래 키를 사용하는 다른 모델의 데이터 참조

변수에 필수 필드를 할당하는 for 루프가 있지만 더 깨끗한 솔루션과 외래 키를 사용하는 솔루션이있는 경우이를 찾고있었습니다.

#MODELS 

class Class1(models.Model): 
    tag_number = models.CharField(max_length = 300, null = True, blank = True) 
    example1 = models.CharField(max_length = 300, null = True, blank = True) 
    example2 = models.CharField(max_length = 300, null = True, blank = True) 

class Class2(models.Model): 
    tag = models.ForeignKey(Class1, related_name = 'tag_foreignkey') 
    example3 = models.CharField(max_length = 300, null = True, blank = True) 
    example4 = models.CharField(max_length = 300, null = True, blank = True) 



#VIEWS - This view is for Class2 but referencing fields from Class1 

tag_number = str(instrumentform.cleaned_data['tag']) 
query_results = Class1.objects.filter(tag_number = tag_number) 
for query_result in query_results: 
     example5 = query_result.example1 
     example6 = query_result.example2 

위의 작품 그러나 나는 일을 장고 방법이 아니다 및 외래 키를 활용하지 않는 가정

여기에 포함 된 코드의 예입니다.

누군가가 나를 올바른 방향으로 이끌어 줄 수 있다면 크게 감사 할 것입니다.

+0

장고에서 ManyToMany 관계를 찾고있을 수도 있습니다. 설명서를 참조하십시오 : https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/ – ruddra

답변

1

만든 희망 , 거기에 몇 가지 누락 된 정보가 있기 때문에 100 %가 원하는 것을 알지 못합니다. Class1의 경우, 외래 키를 사용하여 Class2에 대한 작업을 수행해야합니다.

코드 하단에는 쉬운 방법이 있습니다. (외래 키를 사용했다고 가정하십시오)

tag_number = int(instrumentform.cleaned_data['tag']) 
for query_result in Class1.objects.filter(tag = tag_number).values_list('example1', 'exmaple2'): 
    example5, example6 = query_result 
0

여기에서 성취하려고하는 것이 확실하지 않습니다. 당신이 외래 키를 사용하여

c1 = Class1() 
c2 = Class2() 
c3 = Class2() 
and 
c2.tag = c1 
c3.tag = c1 

이 있다면 나는 당신이 가진 것, 그럼에도 불구하고 그 PstCalc = 클래스 1 을 상상하고 있습니다 :

c1.class2_set = (c2, c3) <- this would be a queryset, not a list 
c2.tag = c1 => c2.tag.example1 = c1.example1 

... 나는 내 자신이 이해 : 아직

관련 문제