2014-09-13 4 views
1

없이 여러 테이블에서 데이터를 검색 나는 다음과 같은 세 가지 일 "예약"할 수 있습니다 모델 여기 category_type 포스트 모델 장고 외래 키 관계

class Post(models.Model): 
    category_type = models.CharField(max_length=10) 
    participant_id = models.IntegerField() 
    title = models.CharField(max_length=200) 

class Book(models.Model): 
    title = models.CharField(max_length=50) 
    author = models.CharField(max_length=500) 
    price = models.IntegerField(default=0) 

class Instrument(models.Model): 
    title = models.CharField(max_length=50) 
    price = models.IntegerField(default=0) 

또는 "악기"가 이러한 범주는 미래에 증가 할 수있다.

게시 테이블의 participant_id 열은 category_type을 기반으로하는 서적 테이블 또는 악기 테이블의 기본 키를 참조합니다.

이제 데이터베이스에서 모든 게시물 및 관련 데이터를 검색하려고합니다.

는 MySQL은,이

select post.title,book.title from post,book where ((post.category_type="book" and post.participant_id=book.id)) 
union 
select post.title,instrument.title from post,instrument where ((post.category_type="instrument" and post.participant_id=instrument.id)) 

처럼 그것을 할 수 있습니다하지만 내가 외래 키 관계를 가질 수 없기 때문에 장고를 사용하여 할 수없는입니다.

도움이 매우 감사합니다.

업데이트 : 나는 다음

class Post(models.Model): 
    category_type = models.CharField(max_length=10) 
    participant_id = models.PositiveIntegerField() 
    content_type = models.ForeignKey(ContentType) 
    participant_object = GenericForeignKey('content_type', 'participant_id')  
    title = models.CharField(max_length=200) 

그리고 아래와 같은 포스트 테이블을 수정하여 장고의 일반적인 관계로 시도 나는 다음과 같은 쿼리

Post.objects.filter(content_type=ContentType.objects.get_for_model(Book)) 

를 발행하지만이 날 오류 준다

FieldError: Cannot resolve keyword 'content_type' into field. Choices are: category_type, id, participant_id, title 

데이터를 조건에 지정할 수없는 경우 어떻게 데이터를 검색 할 수 있습니까?

+1

다른 모델 간의 관계를 만들 수있는 [장고의 일반적인 관계] (https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations)에 관심이있을 수 있습니다. –

+0

안녕하세요. 티미, 장고의 일반적인 관계를 사용하여 시도했지만 그 결과를 검색 할 수 없습니다. 오직 내가 전에 특정 도서 개체를 알고, 그때 유용합니다. 하지만이 일반 관계를 사용하여 데이터를 검색하는 방법을 알아낼 수 없습니다. – Anurag

+0

DB를 다시 작성하지 않은 것처럼 오류가 발생했습니다. – osowskit

답변

1

저는 Timmy가 제안한 장고의 일반적인 관계를 사용했습니다. 포스트

다음
class Post(models.Model): 
    category_type = models.CharField(max_length=10) 
    participant_id = models.PositiveIntegerField() 
    content_type = models.ForeignKey(ContentType) 
    participant_object = GenericForeignKey('content_type', 'participant_id')  
    title = models.CharField(max_length=200) 

그리고에 대한 수정 된 모델이되어 다음 나는이 올바른 결과가 다른 모델을 사용하면됩니다 수정 후 DB를 재 구축하는 것을 잊지 마세요 나에게 준 다음 쿼리

Post.objects.filter(content_type=ContentType.objects.get_for_model(Book)) 

발행 오류가 발생합니다.