如何正确查询manyTOmany模型字段?

时间:2020-04-15 18:32:43

标签: django

好的,这就是我作为开发人员的努力要做的事情。我正在尝试为用户创建收件箱。我有一个Conversation模型,该模型具有多对多字段,然后我有一个InstantMessanger模型,该模型具有sender_id,date和receive_id字段,该字段是Conversation的外键。我想要做的是首先遍历Conversation并显示用户与之有过联系的成员,然后显示一个链接,该链接将您带到该消息的实际内容。但是,我一直坚持让成员展示。我在这里尝试了很多事情,环顾四周,但是我不断收到错误消息,例如“对话”模型不可迭代或无法显示,而是显示为“ dating_app.Profile.none”,对象等。所以我很困在这里,不知道该怎么做。什么是正确的方法?

views.py

def messages(request,profile_id):

    messages = InstantMessage.objects.filter(Q(sender_id=request.user)).\
    values('sender_id','receiver_id', 'message', 'date', ).\
    order_by('date',)


    profile = get_object_or_404(Profile,id=profile_id)

    conversations = Conversation.objects.filter(members=request.user)


return render(request, 'dating_app/messages.html', {'messages': messages,'profile': profile,'conversations':conversations,})

messages.html

{% for conversation in conversations %}
    <li class="text-right list-group-item">
        {% for members in conversation %}{% if members != request.user %}
            {{ members.username }}<br/>
        {% endif %}{% endfor %}

    </li>
{%endfor %}

models.py

class ProfileManager(BaseUserManager):



    def create_user(self, username, email,description,photo, password=None):
        if not email:
            raise ValueError("You must creat an email")
        if not username:
            raise ValueError("You must create a username!")
        if not description:
            raise ValueError("You must write a description")
        if not photo:
            raise ValueError("You must upload a photo")

        user = self.model(
                email=self.normalize_email(email),
                username = username, 
                description= description,
                photo= photo,

            )

        user.set_password(password)
        user.save(using=self._db)
        return user 


    def create_superuser(self, username, email,description,photo, password):
        user = self.create_user(
                email=self.normalize_email(email),
                password=password,
                username=username,
                description=description,
                photo=photo,

            )

        user.is_admin=True
        user.is_staff=True
        user.is_superuser=True
        user.save(using=self._db)
        return user




class Profile(AbstractBaseUser):

    class Meta:
        swappable = 'AUTH_USER_MODEL'


    email                       = models.EmailField(verbose_name="email")
    username                    = models.CharField(max_length=30, unique=True)
    date_joined                 = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login                  = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin                    = models.BooleanField(default=False)
    is_active                   = models.BooleanField(default=True)
    is_staff                    = models.BooleanField(default=False)
    is_superuser                = models.BooleanField(default=False)
    #what I added
    description                 = models.TextField()
    photo                       = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
    matches                     = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='+', blank=True)



    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['description','photo','email']


    objects = ProfileManager()


    def __str__(self):
        return self.username


    def has_perm(self, perm, obj=None):
        return self.is_admin


    def has_module_perms(self,app_label):
        return True



class UserVote(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    voter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='given_vote', on_delete=models.CASCADE)
    vote = models.BooleanField(default=False)

    class Meta:
        unique_together = (('user', 'voter'))


class Conversation(models.Model):
    members = models.ManyToManyField(settings.AUTH_USER_MODEL)




class InstantMessage(models.Model):

    sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'senderr',on_delete=models.CASCADE )
    receiver = models.ForeignKey(Conversation, on_delete=models.CASCADE)
    message = models.TextField()
    date = models.DateTimeField(auto_now_add=True)


    def __unicode__(self):
        return self.message

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式显示成员:

{% for conversation in conversations %}
    <li class="text-right list-group-item">

    {% for member in conversation.members.all %}
        {% if member != request.user %}
            {{ member.username }}<br/>
        {% endif %}
    {% endfor %}
    <li>
{% endfor %}

但是,这将导致一个 N + 1 问题,为了显示成员,您将对每个会话进行一个额外的查询 ,效率不是很高。您可以使用.prefetch_related(..) [Django-doc]来提高效率:

def messages(request,profile_id):
    messages = InstantMessage.objects.filter(Q(sender_id=request.user)).\
    values('sender_id','receiver_id', 'message', 'date', ).\
    order_by('date',)
    profile = get_object_or_404(Profile,id=profile_id)

    conversations = Conversation.objects.filter(
        members=request.user
    ).prefetch_related('members')

    return render(request, 'dating_app/messages.html', {'messages': messages,'profile': profile,'conversations':conversations,})

编辑:您可以通过以下方式按收到的最后一条消息(降序)对消息进行排序:

from django.db.models import Max

def messages(request,profile_id):
    messages = InstantMessage.objects.filter(Q(sender_id=request.user)).\
    values('sender_id','receiver_id', 'message', 'date', ).\
    order_by('date',)
    profile = get_object_or_404(Profile,id=profile_id)

    conversations = Conversation.objects.filter(
        members=request.user
    ).annotate(
        last_message=Max('instantmessage__date')
    ).prefetch_related('members').order_by(
        '-last_message'
    )

    return render(request, 'dating_app/messages.html', {'messages': messages,'profile': profile,'conversations':conversations,})