django.contrib.comments를 사용하면 어쨌든 주석이있는 모델에 역방향 관계를 추가 할 수 있습니까?Django는 반대 관계를 말합니다.
post = Post.objects.all()[0]
comments = post.comments.all()
django.contrib.comments를 사용하면 어쨌든 주석이있는 모델에 역방향 관계를 추가 할 수 있습니까?Django는 반대 관계를 말합니다.
post = Post.objects.all()[0]
comments = post.comments.all()
예, 당신이 할 수 있어야한다 : 예를 들어
장고 워드 프로세서 당
from django.contrib.contenttypes import generic
class Post(models.Model):
...
comments = generic.GenericRelation(Comments)
에 나는 (이 작업을 수행하는 또 다른 방법 함께했다 왜? 그 시간을 할 수있는 다른 방법을 몰랐기 때문에. 시스템의 모든 모델을 파생시킨 추상 모델 클래스가 필요합니다. 추상 모델 자체에는 comments
이라는 메소드가 있는데, 호출시 해당 콘크리트 객체와 관련된 모든 주석 객체 중 QuerySet
을 반환합니다. 따라서 나는 그것을 구현 : '의견 = generic.GenericRelation (댓글, object_id_field ='object_pk ')':
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment
class AbstractModel(models.Model):
def comments(self):
"""Return all comment objects for the instance."""
ct = ContentType.objects.get(model=self.__class__.__name__)
return Comment.objects.filter(content_type=ct,
object_pk=self.id)
class Meta:
abstract = True
, 나는 다음을 사용했다. 분명히'BaseCommentAbstractModel'은 이제'object_id_field'에 대한 비표준 이름을 사용합니까? – tehfink