2011-10-27 2 views
0

가정하자 나는이 모델 (비 실제적인 코드, 그것은 그냥 예)가 :기본 모델과 동일한 추상 모델을 가진 다른 모델의 인스턴스를 비교하는 방법은 무엇입니까?

class BaseArticle(models.Model): 
    title = models.CharField(max_length=512) 
    author = models.ForeignKey(User) 
    content = models.TextField() 

    class Meta: 
     abstract = True 

class ArticleWithColor(BaseArticle): 
    color = models.CharField(max_length=512) 

class ArticleTypeWithSmell(BaseArticle): 
    smell = models.CharField(max_length=512) 

, 나는 기존의 다른 인스턴스가 있는지 여부를 확인하고자하는 아티클 저장 (색상 또는 제 냄새)가 (BaseArticle 필드 인) 공유 필드에 대해 동일한 값을가집니다.

다른 말로하면, 내가 저장하려고하는 ArticleWithSmell처럼 BaseArticle에서 상속 한 필드에 대해 동일한 값을 가진 ArticleWithColor가 이미 있는지 확인할 수 있습니까?

답변

0

데이터 복제를 막으려 고한다면 unique_together 옵션을 사용할 수 있습니다. 그렇지 않으면 model_to_dict (django.forms.models import model_to_dict에서)를 사용하여 모델 속성을 가져와 비교합니다. 나는 그것이 pk/id를 dict의 일부로 반환하는지 확실하지 않지만, 그렇다면 비교하기 전에 그것을 제거해야한다.

+0

'unique_together'이이 개 테이블에서 작동하지 않습니다

당신은 아마 그 라인을 따라 뭔가 (아직 테스트하지)를 할 수 있습니다. – Etienne

+0

내 주요 문제는 모델 속성이 추상 모델에서 파생되었는지 여부와 이러한 속성이 추상 모델에서 파생 된 다른 모델에서 동일한 값을 갖는지 여부를 확인할 수 있기를 바랍니다. – LaundroMat

0

모든 어린이 모델을 쿼리 할 수 ​​있도록 답변을 업데이트했습니다. 그것이 모델리스트를 만드는 유일한 방법 일뿐입니다. 사용 사례에 따라 다릅니다.

class BaseArticle(models.Model): 
    title = models.CharField(max_length=512) 
    author = models.ForeignKey(User) 
    content = models.TextField() 

    _childrens = set() 

    # register the model on init 
    def __init__(self, *args, **kwargs): 
     super(BaseArticle, self).__init__(*args, **kwargs) 
     BaseArticle._childrens.add(self.__class__) 

    def save(self, *args, **kwargs): 
     for model in BaseArticle._childrens: 
      query = model.objects.filter(title=self.title, author=self.author, content=self.content) 
      # if this Article is already saved, exclude it from the search 
      if self.pk and model is self.__class__: 
       query.exclude(pk=self.pk) 
      if query.count(): 
       # there's one or more articles with the same values 
       do_something() 
       break 
     super(BaseArticle, self).save(*args, **kwargs) 

    class Meta: 
     abstract = True 
+0

'self.objects.filter'는'BaseArticle'에서 상속받은 다른 모델이 아닌 동일한 모델의 인스턴스만을 필터링합니다. – Alasdair

+0

오, 그래! 너는 완전히 옳다. 이 문제에 대해 생각해 보겠습니다. – Etienne

+1

해결할 답변을 업데이트했습니다. – Etienne

관련 문제