2012-07-28 2 views
1

Django 일반 외래 키와 관련된 이상한 문제가 있습니다. 생성자를 사용하여 할당하면 일반 필드가 고정되지 않습니다. 그것은 단지 사후 건설을 고수 할 것입니다. 이것에 대한 정보를 찾을 수 없으므로 이에 대한 새로운 질문을 만들고 있습니다. 왜 이런 일이 발생하는지 알고 싶습니까?Django 일반 외래 키 필드는 건설 중 할당되지 않았지만 사후 작업을 할당 할 수 있습니다.

아래는 여기에 내 수업

class Answer(models.Model): 
    question = models.OneToOneField(Question) 
    date = models.DateField() 

    # Generic relation to contain heterogeneous data of class *Data 
    content_type = models.ForeignKey(ContentType) 
    object_id = models.PositiveIntegerField() 
    answer_data = generic.GenericForeignKey('content_type', 'object_id') 

    def __unicode__(self): 
     question = "" 
     if hasattr(self, 'question'): 
      question = self.question.__unicode__() 
     else: 
      question = "Question undefined" 

     answer = "" 
     if hasattr(self, 'answer_data'): 
      answer = self.answer_data.__unicode__() 
     else: 
      answer = "Answer undefined" 

     return "Question: {" + question + "}; Answer: {" + answer + "}" 

내 쉘 문제를 보여줍니다 세션 :

>>> from nequals1.models import * 
>>> import datetime 
>>> q = Question(text="Is this a question?") 
>>> d = CharData(data="Yes, this is a question") 
>>> a = Answer(question=q, date = datetime.datetime.now(), answer_data=d) 
>>> a 
Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
    File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 373, in __repr__ 
    u = unicode(self) 
    File "/Users/kheck/PycharmProjects/neq1/nequals1/models.py", line 30, in __unicode__ 
    answer = self.answer_data.__unicode__() 
AttributeError: 'NoneType' object has no attribute '__unicode__' 
>>> a.answer_data=d 
>>> a 
<Answer: Question: {Is this a question?}; Answer: {Yes, this is a question}> 

답변

2

당신은 d을 저장하지 않은를 (또는 그 문제에 대한 항목 중), 그래서 일반 관계의 object_id 필드에서 사용할 수있는 ID는 없습니다. 그것을 a에 할당하기 전에 먼저 저장하십시오.