ユーザーのプロファイルを一覧表示しようとしています。ユーザーの同じ都市のプロファイルが最初に来て、次に優先順位が州、次に国、最後に残りのプロファイルになるようにリストしたいと思います。これは私が試したことです。モデル
class Profile(models.Model):
uuid = UUIDField(auto=True)
user = models.OneToOneField(User)
country = models.ForeignKey(Country, null=True)
state = models.ForeignKey(State, null=True)
city = models.ForeignKey(City, null=True)
views.py current_user = Profile.objects.filter(user = request.user)
profiles_city = Profile.objects.filter(city=current_user.city)
profiles_state = Profile.objects.filter(state=current_user.state)
profiles_country = Profile.objects.filter(country=current_user.country)
profiles_all = Profile.objects.all()
profiles = (profiles_city | profiles_state | profiles_country | profiles_all).distinct()
ただし、Profile.objects.all()と同じ結果が得られます。
私を助けてください。前もって感謝します
渡されたパラメータに基づいてオブジェクトを順序付けるorder_by
メソッドが必要QuerySet
です。これはデータベースで行われます:
Profile.objects.order_by(
'current_user__city',
'current_user__state',
'current_user__country',
)
編集:
あなたがでソートしたい場合はcity
、state
とcountry
の名前は、ユーザーにログインし、あなたが使用して、Pythonのレベルでこれを行うことができsorted
、およびカスタムkey
呼び出し可能:
from functools import partial
def get_sort_order(profile, logged_in_profile):
# This is a simple example, you need to filter against
# the city-state-country combo to match precisely. For
# example, multiple countries can have the same city/
# state name.
if logged_in_profile.city == profile.city:
return 1
if logged_in_profile.state == profile.state:
return 2
if logged_in_profile.country == profile.country:
return 3
return 4
logged_in_profile = request.user.profile # logged-in user's profile
get_sort_order_partial = partial(get_sort_order, logged_in_profile=logged_in_profile)
sorted(
Profile.objects.all(),
key=get_sort_order_partial,
)
使用して、データベースレベルで同じことをCase
してWhen
はPythonを持っているif
- elif
-else
構文のように:
from django.db.models import Case, When, IntegerField
Profile.objects.order_by(
Case(
When(city=logged_in_profile.city, then=1),
When(state=logged_in_profile.state, then=2),
When(country=logged_in_profile.country, then=3),
default=4,
output_field=IntegerField(),
)
)
これにより、クエリセットが作成され、すべての操作がデータベースで実行されるため、より高速になるという追加の利点もあります(SELECT CASE WHEN ...
)。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加