【发布时间】:2026-02-17 14:40:02
【问题描述】:
假设我们有两个模型 Account 和 Profile:
class Profile < ApplicationRecord
belongs_to :account
scope :age_upper, ->(age) { where("age > ?", age) }
end
class Account < ApplicationRecord
has_one :profile
end
然后我们可以像这样在 Rails 中查询 Account 模型:
>>> Account.joins(:profile).merge(Profile.age_upper(18))
但是对于 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
我的问题是我们可以使用 Profile 的过滤器 age_upper 从 Account 查询,而不是像下面那样为 Account 重写另一个
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)()
【问题讨论】:
标签: python ruby-on-rails django orm