Django模型ManyToMany反向过滤器

时间:2018-01-12 00:56:36

标签: python django filter manytomanyfield

这里的摘录(类似于我的模特):

class Person(models.Model):
  name = models.CharField(max_length=20)
  relationships = models.ManyToManyField('self',
    through='Relationship',
    symmetrical=False,
    related_name='related_to',
  )
  def __str__(self):
    return self.name

class Relationship(models.Model):
  from_person = models.ForeignKey(Person,
    related_name='from_people',
    on_delete=models.CASCADE,
  )
  to_person = models.ForeignKey(Person,
    related_name='to_people',
    on_delete=models.CASCADE,
  )
  status = models.CharField(max_length=20)
  def __str__(self):
    return "{} is {} {}".format(
      self.from_person.name, self.status, self.to_person.name)

这是我数据库的内容:

>>> Person.objects.all()
<QuerySet [<Person: A>, <Person: B>, <Person: C>]>
>>> Relationship.objects.all()
<QuerySet [<Relationship: B is Following C>]>

如果我想查看某个人关注的是谁,我可以在Person类中构建一个新方法:

def get_following(self):
  return self.relationships.filter(
    to_people__status='Following',
    to_people__from_person=self)

这有效:

>>> p2.get_following()
<QuerySet [<Person: C>]>

我想做这个的逆转。而不是问这个人是谁?&#34;,我想问问&#34;谁跟随这个人?&#34;。我可以这样做(虽然它返回Relationship对象,而不是Person对象):

>>> Relationship.objects.filter(to_person=p3, status='Following')
<QuerySet [<Relationship: B is Following to C>]>

我的尝试就是这个(它返回一个空的QuerySet):

def get_following(self):
  return self.relationships.filter(
    from_people__status='Following',
    from_people__to_person=self)

感谢您的帮助!

编辑: 这是我选择的答案:

def get_followers(self):
  return self.related_to.filter(from_people__status='Following')

4 个答案:

答案 0 :(得分:1)

以防万一其他人需要完全按照您描述的方式来实现“跟随者”的另一种方式,但是使用不同的建模方案:

# project/account/models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from model_utils import Choices

class User(AbstractBaseUser, PermissionsMixin):
    class Meta:
        # ...

    username = models.CharField(...)
    email = models.EmailField(...)
    # ...

    ### Custom app-specific relationships (database scheme) ###

    # symmetrical=False is needed for this reason: https://stackoverflow.com/a/42040848/3433137
    following = models.ManyToManyField('self', related_name='followers', blank=True, symmetrical=False)
# project/account/forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.admin.widgets import FilteredSelectMultiple
from .models import User

class UserChangeForm(forms.ModelForm):
    # ...

    # new:
    following = forms.ModelMultipleChoiceField(
        queryset=User.objects.all(),
        required=False,
        widget=FilteredSelectMultiple(
            verbose_name='Following',
            is_stacked=False
        )
    )
    # new:
    followers = forms.ModelMultipleChoiceField(
        queryset=User.objects.all(),
        required=False,
        widget=FilteredSelectMultiple(
            verbose_name='Followers',
            is_stacked=False
        )
    )

    class Meta:
        model = get_user_model()
        # add 'following' and 'followers' to the fields:
        fields = ('email', 'password', ..., 'following', 'followers')

    # also needed to initialize properly:
    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)

        # Filter out the self user in the lists and initialize followers list:
        if self.instance and self.instance.pk:
            self.fields['following'] = forms.ModelMultipleChoiceField(
                queryset=User.objects.all().exclude(pk=self.instance.pk),
                required=False,
                widget=FilteredSelectMultiple(
                    verbose_name='Following',
                    is_stacked=False
                )
            )
            self.fields['followers'] = forms.ModelMultipleChoiceField(
                queryset=User.objects.all().exclude(pk=self.instance.pk),
                required=False,
                widget=FilteredSelectMultiple(
                    verbose_name='Followers',
                    is_stacked=False
                )
            )
            self.fields['followers'].initial = self.instance.followers.all()
# project/account/admin.py
from django.contrib.auth import get_user_model
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User
from .forms import UserChangeForm, UserCreationForm


class Admin(BaseUserAdmin):
    add_form = UserCreationForm
    form = UserChangeForm
    model = get_user_model()

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ['email', 'username', 'is_admin']
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('username',)}),
        ('Permissions', {'fields': ('is_admin', 'is_superuser', 'is_staff')}),
        # new:
        ('Following / Followers', {'fields': ('following', 'followers')}),
    )
    # other fields
    # ...

    # new:
    filter_horizontal = ('following', 'followers')

admin.site.register(User, Admin)
admin.site.unregister(Group)

如果然后启动服务器并转到localhost:8000 / admin / 并导航到用户的详细信息页面,您应该在屏幕上看到以下内容:

enter image description here

我没有添加计数器,因此您可以在list_view中一次看到关注者的数量。

请注意,在管理面板中,带有跟随者的第二个FormField是只读的。用户无法选择其他用户来关注他。

答案 1 :(得分:0)

查看this文档。否则这里有一些其他方法......

self.relationships.from_people.objects.all()会返回所有带有相关名称from_people的对象。

但是,我会略微改变一些代码,以便使用self.relationships.from_people.objects.filter(status='Following')

另一种方法(尽管不是最有效的)是传入人物模型,并使用person.pk作为过滤器传递关系模型。

def get_following(self, pk):
    person = Person.objects.get(pk=pk)
    relationships = Relationship.objects.filter(to_person=person.id)
    return relationships

答案 2 :(得分:0)

你有一个像这样的QuerySet:<QuerySet [<Relationship: B is Following C>]>。想想有一天(我猜这是建议的)'人'有很多粉丝,它可能会回复这么多粉丝,如:<QuerySet [<Relationship: B is Following C>, <Relationship: A is Following C>]>。 所以,我会使用values_list()[1]:

Relationship.objects.filter(to_person=p3, status='Following').values_list('from_person__name', flat=True)

返回:<QuerySet [A, B, ...]>

如果只传入一个字段,也可以传入flat参数。如果为True,则表示返回的结果是单个值,而不是一个元组。

或创建方法:

def get_followers(self):
    follower_of_person = []
    for value in relation_of_person:
        follower_of_p3.append(value.from_person.name)
    return follower_of_person

返回:[A, B, ...]

values_list仍然更好,因为您直接在数据库上工作。

[1] https://docs.djangoproject.com/en/2.0/ref/models/querysets/#values-list (这里有很多ManyToMany的例子)。

答案 3 :(得分:0)

这是我选择的答案:

def get_followers(self):
  return self.related_to.filter(from_people__status='Following')