簡體   English   中英

如何按配置文件 model (1:1) 中的字段對用戶 model 進行排序?

[英]How do I sort the user model by fields in the profile model (1: 1)?

Skill_note_reputation 是 Profile model 中的一個字段,與 Profileuser 具有 1:1 的關系。

如何按 Skill_note_reputation 值對用戶模型進行排序?

    user_list = User.objects.all ()

感謝您讓我知道如何解決它

如果將parent_link=True鍵添加到OneToOneField ,則可以引用Profileuser中的字段,就好像它們屬於User model 一樣。

例如:

class Profileuser(models.Model):
    user = models.OneToOneField(
          User, on_delete=models.CASCADE,
          related_name='profileuser', parent_link=True)
    skill_note_reputation = models.IntegerField()

現在,您可以像這樣過濾您的User model:

User.objects.filter(skill_note_reputation=1)

對於更Pythonic的方法,您可以利用 Django 的model inheritance ,並將您的Profileuser model 變成這樣:

class Profileuser(User):
    skill_note_reputation = models.IntegerField()

注意這個model和上面的model是一樣的。

如果出於某種原因您不想使用parent_link=True ,您可以使用 Django 的LOOKUP_SEP引用任何ForeignKey列,如下所示:

User.objects.filter(profileuser__skill_note_reputation=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM