0

I have developed a Python-Flask app using Mongoengine and mongodb as my database.
I want to query my database and get all tickets of all users which have role of 'user'.
here is my db modal for tickets and users:

class TicketReply(EmbeddedDocument):
    content = StringField(required=True, max_length=2000)
    date = ComplexDateTimeField(required=True)
    user = StringField(required=True, max_length=30)
    fileAttached = StringField(max_length=500)


class Ticket(EmbeddedDocument):
    subject = StringField(required=True, max_length=200)
    content = StringField(required=True, max_length=2000)
    department = StringField(required=True, max_length=20)
    status = StringField(required=True, max_length=20)
    createdDate = ComplexDateTimeField(required=True)
    fileAttached = StringField(max_length=500)
    id = StringField(max_length=500, required=True)
    replies = EmbeddedDocumentListField(TicketReply)


class Users(UserMixin, Document):
    fullName = StringField(required=True, max_length=200)
    email = EmailField(required=True, unique=True)
    phone = StringField(required=True, max_length=11, min_length=11, unique=True)
    password = StringField(required=True, max_length=500)
    registerDate = ComplexDateTimeField(required=True)
    role = StringField(required=True, max_length=20)
    tickets = EmbeddedDocumentListField(Ticket)

This is how I get a certain user tickets:

user = Users.objects(email=current_user.email).first()
        getTickets = user.tickets

But I have no idea how to get all tickets of all users with role of 'users'.
Any help is appreciated.

1 Answers1

1

If I understand correctly, you want all tickets, from all users with a certain role. Since the tickets are nested (by the use of EmbeddedDocument) in the User's Documents, one way is this:

admin_tickets = []
for user in User.objects(role='admin'):
    admin_tickets += user.tickets

Or If you want to improve a bit the performance and don't need the users info, you can use scalar:

admin_tickets = []
for user_tickets in User.objects(role='admin').scalar('tickets'):
    admin_tickets += user_tickets
bagerard
  • 5,681
  • 3
  • 24
  • 48
  • I'm wondering is there any way I can get tickets user or not? I mean now I have all tickets of my users, then how I can know these tickets are belong to which user? – Mohammad Ghonchesefidi Jun 15 '19 at 10:32
  • 1
    have a look at this, even if its simplified, I hope it will help you to see the different options you have: https://gist.github.com/bagerard/a7dc0b63dcfcfa1d48ff509774270d28 I recommend option 1 or 2, 3 is a bit clumpsy – bagerard Jun 15 '19 at 12:20