简体   繁体   中英

Django models query

I have a django model something like

messageto:
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.

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.

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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