Django模块多对多相反过滤器(Django Model ManyToMany Reverse F

2019-09-29 00:59发布

下面是从(东西类似)我的模型摘录:

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>]>

我想要做的这个相反。 不要问“谁这个人跟着我来?”,我想问“谁遵循这个人吗?”。 我是这样做的(虽然它返回的关系对象,而不是Person对象):

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

我尝试的(这将返回一个空查询集):

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')

Answer 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 /管理/并导航到用户的详细页面,你会看到这样的事情在屏幕上:

所以你能看到追随者量一次在list_view我没加计数器。

需要注意的是与追随者第二FormField是只读的管理面板。 用户不能选择其他用户跟随他。



Answer 2:

你有一个查询集是这样的: <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, ...]>

如果你只有在一个单场传球,你也可以通过在平坦的参数。 如果属实,这将意味着返回的结果是单值,而不是一个元组。

或创建一个方法:

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 (这里有多对多的一个很好的例子)。



Answer 3:

看看这个文件。 否则,这里有一些其他的方法?

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


Answer 4:

这是我选择的答案:

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


文章来源: Django Model ManyToMany Reverse Filter