2017-12-27 34 views
0

우리가이 개 모델을 말해봐 범위 계정과 프로필을 병합 그러나 Django의 경우 :장고 전화 관련 모델의 검색어는 액티브

class ProfileQuerySet(models.QuertSet): 
    def age_upper(age): 
     return self.filter(age__gt=age) 

class Profile(models.Model): 
    account = models.ForiegnKey('Account', on_delete=models.CASCADE) 

    objects = models.Manager.from_queryset(ProfileQuerySet)() 


class Account(models.Model): 
    pass 

내 질문에 필터를 사용하여 계정에서 쿼리 할 수 ​​있습니다. 프로필 10 대신

class AccountQuerySet(models.QuertSet): 
    def age_upper(age): 
     return self.filter(profile__age__gt=age) 

class Account(models.Model): 
    objects = models.Manager.from_queryset(AccountQuerySet)() 

답변

0

이 레일에서, 당신은 (적어도 액티브과) 다른 쿼리 하나 개의 모델의 범위를 사용할 수 없습니다 아래에 같은 계정에 대한 또 다른 하나를 다시 작성합니다. 그리고 이것을 수행하는 방법을 찾더라도이를 달성하는 최선의 방법은 아닐 것입니다.

당신은 당신이 그런 우려 사용할 수 있습니다 다시 범위 또는 다른 공유 논리를 작성하지 않으려면 :

# app/models/profile.rb 
class Profile < ApplicationRecord 
    include SharedScopes 
    belongs_to :account 
end 

# app/models/account.rb 
class Account < ApplicationRecord 
    include SharedScopes 
    has_one :profile 
end 
:이 동작을 필요로하는 곳에

# app/models/concerns/shared_scopes.rb 
module SharedScopes 
    extend ActiveSupport::Concern 

    included do 
    scope :age_upper, ->(age) { where("age > ?", age) } 
    end 
end 

을 그리고 모든 모델에서이 문제를 포함

+0

아마 내 질문에 대한 오해가 생겼다. 나는 장고에서 레일스 같은 쿼리를 수행하기를 원한다. 그리고 btw, 당신의 대답에, 내가'Account.age_upper (18)'을하면'Account'에'age' 속성이 없기 때문에 에러가 발생합니다. – arshavindn