2013-08-14 12 views
6

" dizisine çözümleyemiyorum. Soru ve Yanıt modelleri için Oylama modelini tanımlamak üzere Django'nun Genel İlişkilerini kullanıyorum. İşte Django Genel İlişkiler hatası: "content_object" anahtar kelimesini "

oyumu modelidir:

models.py

class Vote(models.Model): 
    user_voted = models.ForeignKey(MyUser) 
    is_upvote = models.BooleanField(default=True) 

    # Generic foreign key 
    content_type = models.ForeignKey(ContentType) 
    object_id = models.PositiveIntegerField() 
    content_object = generic.GenericForeignKey('content_type', 'object_id') 

    class Meta: 
     unique_together = ('content_type', 'user_voted') 



views.py

 user_voted = MyUser.objects.get(id=request.user.id) 
     object_type = request.POST.get('object_type') 

     object = None; 
     if object_type == 'question': 
      object = get_object_or_404(Question, id=self.kwargs['pk']) 
     elif object_type == 'answer': 
      object = get_object_or_404(Answer, id=self.kwargs['pk']) 

     # THIS LAST LINE GIVES ME THE ERROR 
     vote, created = Vote.objects.get_or_create(user_voted=user_voted, content_object=object) 



Sonra bu hatayı alıyorum:

FieldError at /1/ 
Cannot resolve keyword 'content_object' into field. Choices are: answer, content_type, id, is_upvote, object_id, question, user_voted 



Django konsola "nesne" yazdırdığınızda, bu "Soru 1" nesne yazdırır. Satır "content_object = nesne" Bana saha hata veriyor neden yüzden ...

Herhangi fikirleri anlamıyorum: (((???

Teşekkür

cevap

14

content_object okuma bir çeşit alanlar content_type ve object_id tarafından belirtilen nesneyi alır -sadece nitelik aşağıdaki kodunuzu değiştirmeniz gerekir.

from django.contrib.contenttypes.models import ContentType 
type = ContentType.objects.get_for_model(object) 
vote, created = Vote.objects.get_or_create(user_voted=user_voted, content_type=type, object_id=object.id) 

Düzenleme: Django documentation açıkça belirtiyor:

Due to the way GenericForeignKey is implemented, you cannot use such fields directly with filters (filter() and exclude(), for example) via the database API. Because a GenericForeignKey isn’t a normal field object, these examples will not work:

# This will fail 
>>> TaggedItem.objects.filter(content_object=guido) 
# This will also fail 
>>> TaggedItem.objects.get(content_object=guido)