简体   繁体   English

Django模型查询

[英]Django models query

I have a django model something like 我有一个类似的Django模型

messageto: messageto:
messagefrom: messagefrom:
message: 信息:

The thing is when I have to display messages between two particular users , I have to go through all messages stored in the database and check both messageto and messagefrom fields. 问题是当我必须在两个特定用户之间显示消息时,我必须遍历数据库中存储的所有消息,并检查messageto和messagefrom字段。

The way I have worked with django is like each model represents a table, and corresponding to each object of the model class we have a row in the database. 我使用django的方式就像每个模型都代表一个表,并且对应于模型类的每个对象,我们在数据库中都有一行。

So according to this logic having a separate table for each messageto and messagefrom combo is not possible I think as we need to declare a separate class for each of them. 因此,根据这种逻辑,我认为不可能为每个messageto和messagefrom组合使用单独的表,因为我们需要为它们中的每个声明一个单独的类。

Is there a way I can find the messages between the users without going through every message? 有没有一种方法可以查找用户之间的消息而无需遍历每条消息?

I am looking for either some way with same implementation or a new implementation any is fine. 我正在寻找使用相同实现或新实现的任何方式都可以。

Please help. 请帮忙。

One way would be to use Q objects to solve that issue. 一种方法是使用Q对象解决该问题。 If your model is named Message, you could use the following query to have all the messages exchanged between two users A and B: 如果您的模型名为Message,则可以使用以下查询在两个用户A和B之间交换所有消息:

Message.objects.filter(Q(messageto=A, messagefrom=B)|Q(messageto=B, messagefrom=A)) Message.objects.filter(Q(messageto = A,messagefrom = B)| Q(messageto = B,messagefrom = A))

See https://docs.djangoproject.com/en/1.10/topics/db/queries/#complex-lookups-with-q-objects for more details on Q objects. 有关Q对象的更多详细信息,请参见https://docs.djangoproject.com/en/1.10/topics/db/queries/#complex-lookups-with-q-objects

Database doesn't iterate through everything. 数据库不会遍历所有内容。 It keeps the records indexed. 它使记录保持索引。

you can have a model for users( if not django provides one default User model). 您可以为用户提供一个模型(如果没有,django提供一个默认的用户模型)。

class Users(models.Model):
    # all the fields you want for a user(username, password, email,etc..)
    message_exchanged=models.ManyToManyField(Messages,through='MessageMap',through_fields=('messagefrom','message'))

then you can have a class for storing messages. 那么您可以拥有一个用于存储消息的类。

class Messages(models.Model):
    message_text=models.TextField()
    #other fields you want to add for a message

here you have your MessageMap model 这是您的MessageMap模型

class MessageMap(models.Model):
messagefrom=models.ForeignKey(Users)
message=models.ForeignKey(Message)
messageto=models.ForeignKey(User,related_name='next_messsage',null=True,blank=True)

and once you store the messages. 并且一旦您存储了消息。 you can query messages using 您可以使用以下方式查询消息

messages=Message.objects.filter(Q(messagefrom = from_user),Q(messageto=to_user))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM