다음과 같은 열이 있다고 가정합니다.
num_member = tables.Column(accessor = 'members.count', verbose_name = 'number of members' )
템플릿에서 이것을 정렬하려고하면 다음이 발생합니다.
Field Error: Cannot resolve keyword u'count' into field
문서를 읽었고 order_by
일종의을 전달하여 사용할 수 있다고하는데 accessor
, 정확히 어떻게해야합니까?
Model의 속성 메서드와 같은 기능의 경우 accessor
. 예를 들면 :
Class MyModel(models.Model):
data= models.CharField(max_length=255)
@property
def print_function(self):
return 'hello world'
#Table class
class MyTable(tables.Table):
data= tables.Column(accessor='print_function')
class Meta:
model = MyModel
fields = ('data')
위의 방법을 사용하면 접근자를 사용하여 테이블에 다양한 종류의 데이터를 표시 할 수 있습니다.
Class SomeModel(models.Model):
some_data= models.CharField(max_length=255)
data= models.ManyToManyField(MyModel)
@property
def count_function(self):
some_data= self.data.objects.count() #returns count of the objects
return some_data
#Table class
class SomeTable(tables.Table):
data= tables.Column(accessor='count_function')
class Meta:
model = SomeModel
fields = ('data')
접근자는 다음과 같이 관련 foreignkey 모델의 필드 값에 직접 접근하는 데 사용할 수 있습니다.
Class SomeModel(models.Model):
somedata= models.ForeignKey(MyModel)
#Table class
class MyTable(tables.Table):
data= tables.Column(accessor='somedata.data')
class Meta:
model = SomeModel
fields = ('data')
편집하다
order_by
사용 방법에 대한 예를 들어 보겠습니다 .
#Class Based view, I am subclassing ListView and SingleTableView here for example
class MyView(ListView, SingleTableView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['table'].order_by = '-last_updated' #last_updated is a datetimefield in model
return context
위 코드에서 내가 한 것은 나중에 템플릿에서 렌더링 될 컨텍스트에서 테이블 데이터의 순서를 변경하는 것입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다