2017-09-06 1 views
0

내가 하나를 추가해야 AdAdmin에서 .extra()장고 - 관리자 ListFilter 검색어 세트에 witn의의 .extra()

를 사용하여 검색어 세트에 장고 관리자 list_filter을 사용하는 방법을 알아 내려고 하루 이상 모델 AdHist에서 새 열 'ad_hist_status_id은'그래서 나는 SomeListFilter에 코드의이 부분을 사용할 수 있습니다 : 그것은 불가능처럼 보이는

def queryset(self, request, queryset): 
    return queryset.filter(ad_hist_status_id=self.value()) 

. SQL로 이렇게하는 것은 간단하다

select a.*, ah.ad_hist_status_id from ad_ad a 
join ad_adhist ah on ah.ad_id = a.id 
where 
ah.datetime_end is null 
order by a.id DESC 

지금까지 내가 장고 관리자에서이 SomeListFilter을 작업 할 수없는 오류는 다음과 같습니다

FieldError at /admin/ad/ad/ 

Cannot resolve keyword 'ad_hist_status_id' into field. 
Choices are: addetailscategories, address, adhist, adphotos, 
adprice, adscheduleinfo, age, comment, county, county_id, 
date_inserted, date_updated, description, district, district_id, 
email, id, lat, lng, name, parish, parish_id, schedule_type, 
schedule_type_id, telephone, title, user_inserted, user_inserted_id, 
user_updated, user_updated_id 

내 질문은, 내가 효과적으로 새를 추가하려면 어떻게 열을 QuerySet에 추가 한 다음이 새 QuerySet을 새 열로 어떻게 쿼리 할 수 ​​있습니까?

모델 울부 짖는 소리 내 코드의

일부 부분 :

class Ad(models.Model): 
    title = models.CharField(max_length=250) 
    name = models.CharField(max_length=100) 
    description = models.TextField() 
    age = models.IntegerField(blank=True, null=True) 
    telephone = models.CharField(max_length=25) 
    email = models.EmailField() 
    district = models.ForeignKey(District) 
    county = ChainedForeignKey(County, chained_field="district", chained_model_field="district", sort=True) # smart_selects app 
    parish = ChainedForeignKey(Parish, chained_field="county", chained_model_field="county", sort=True) # smart_selects app 
    address = models.CharField(max_length=250, null=True, blank=True) 
    lat = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) 
    lng = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) 
    schedule_type = models.ForeignKey(AdScheduleType) 
    comment = models.TextField(null=True, blank=True) 
    user_inserted = models.ForeignKey(User, null=True, blank=True, related_name='user_inserted_ad') 
    date_inserted = models.DateTimeField(auto_now_add=True) 
    user_updated = models.ForeignKey(User, null=True, blank=True, related_name='user_updated_ad') 
    date_updated = models.DateTimeField(null=True, blank=True) 

    def __str__(self): 
     return self.name 

class AdHist(models.Model): 
    ad = models.ForeignKey(Ad) 
    datetime_begin = models.DateTimeField() 
    datetime_end = models.DateTimeField(null=True, blank=True) 
    ad_hist_status = models.ForeignKey(AdHistStatus) 
    ad_hist_change_reason = models.ForeignKey(AdHistChangeReason) 
    comment = models.TextField(null=True, blank=True) 
    user_inserted = models.ForeignKey(User, null=True, blank=True, related_name='user_inserted_ad_hist') 
    date_inserted = models.DateTimeField(auto_now_add=True) 
    user_updated = models.ForeignKey(User, null=True, blank=True, related_name='user_updated_ad_hist') 
    date_updated = models.DateTimeField(null=True, blank=True) 

    def __str__(self): 
     return self.ad.name 

관리자 :

class SomeListFilter(admin.SimpleListFilter): 
    title = _('Approval State') 
    parameter_name = 'ad_hist_status_id' 

    def lookups(self, request, model_admin): 
     return (
      ('1', _('Approved')), 
      ('4', _('Not Approved')), 
     ) 

    def queryset(self, request, queryset): 
     return queryset.filter(ad_hist_status_id=self.value()) 

class AdAdmin(admin.ModelAdmin): 
    list_display = ('id', 'name', 'title', 'age', 'telephone', 
        'email', 'district', 'county', 'parish', 
        'ad_status', 'ad_hist_change_reason', 'comment', 
        'user_inserted', 'date_inserted', 'user_updated', 
        'date_updated', 'ad_hist_status_id') 

    readonly_fields = ('ad_status', 'id', 'ad_hist_change_reason', 
        'ad_hist_status_id') 

    list_filter = (SomeListFilter,) 

    def get_queryset(self, request): 
     qs = super(AdAdmin,self).get_queryset(request).extra(select={'ad_hist_status_id': 'select ad_hist_status_id from ad_adhist where ad_adhist.ad_id = ad_ad.id and ad_adhist.datetime_end is null'},) 
     return qs 

    def ad_hist_status_id(self, inst): 
     return inst.ad_hist_status_id 

누군가가 나에게 단서를 줄 수 있습니까? 내가 바로 질문을 이해한다면

안부

답변

0

, 당신이 찾고 있습니다 :

from django.db.models import F 

def queryset(self, request, queryset): 
    return queryset.filter(ad_hist_status__id=F('id')) 

F expression을 같은 모델에서 필드를 참조하는 데 사용되며,에서 필드를 참조 관련 모델에서는 밑줄 (_)을 사용해야합니다.

+0

안녕하세요 Ankur합니다. 답장을 보내 주셔서 감사합니다. 모델 Ad는 작동하지 않았지만 AdHist를 가리키는 키가 없으며 AdHist 만 Ad을 가리 킵니다. 모든 단서? –

+0

이것을 시도 했습니까? AdHist에는 Ad에 대한 외래 키가 있습니다. 즉, AdHist에 액세스 할 수 없다는 의미는 아닙니다. 이것을 시도한 후에 확인하십시오. –

0

Django field lookups을 자세히 살펴보십시오. 문서가 말하는 것을보세요 :

기본 검색 키워드 인수는 field__lookuptype=value의 형식을 취합니다. (두 줄로 밑줄입니다.)

당신은 관련 AdHistStatus을 가지고 Ad,에서 AdHist 관련 객체를 받아, 그 id을 싶어.

그래서 당신처럼이 id 필드에 액세스해야합니다

def ad_hist_status_id(self, instance): 
    return instance.adhist.ad_hist_status.id 

아니면 이중 밑줄 구문을 직접 표시 할 수 있습니다

class AdAdmin(admin.ModelAdmin): 
    list_display = (..., 'adhist__ad_hist_status__id') 
+0

안녕하세요. 답장을 보내 주셔서 감사합니다. 그것은 작동하지 않습니다, 나에게 같은 오류를 제공합니다.모델 Ad를보고 AdHist를 가리키는 키가 없으면 AdHist 만 Ad을 가리 킵니다. 모든 관습에 대한 단서? –

+0

@ André 나는 이제 내가 여기에서 문제를 발견했다고 생각한다. 'AdHist' 모델은'Ad'와 외래 키 관계를 가지고 있습니다. 이것은 ** 하나의'Ad'에 많은 AdHist' **가 있음을 의미합니다 **. 그래서 당신은 당신의'Ad' 인스턴스에'AdHist' 항목 목록을 가지고 있습니다. 당신은'ad.adhist_set'에 의해 접근 할 수 있습니다. 'ForeignKey' 대신'OneToOne' 관계를 원한다고 생각하십시오. – wencakisa

+0

안녕하세요 wencakisa. AdHist에는 Ad에 대한 핵심 참조가 하나 이상 있으므로 OneToOne은 작동하지 않습니다. 더 이상의 단서? –