Many-to-many modeling with relationship data in the Google App Engine

I have two models in my application, Transaction and Person, with a many-to-many relationship. Each Transaction includes individuals. For each person, there is also an amount associated with each transaction with which the person is associated. Therefore, I need to model the many-to-many relationship with the relationship data. Google offers this approach:

http://code.google.com/intl/sv-SE/appengine/articles/modeling.html

With this approach, I have this model:

class TransactionPerson(db.Model): # References transaction = db.ReferenceProperty(Transaction, required=True) person = db.ReferenceProperty(Person, required=True) # Values amount = db.FloatProperty(required=True) 

But I believe that this is very bad for performance, because if I need to sum the sum for each Person in all transactions, I need to run the Person * Transaction * TransactionPerson cycle to implement the "merge" when summing the sums.

MY IDEA

My idea is to have two lists in the transaction model:

 class Transaction(db.Model): persons = ListProperty(db.Key) persons_amount = ListProperty(float) 

This way, I don’t need to iterate over all TransactionPerson transactions for each Person to find the related transaction. And I can still request transactions based on Person.

QUESTIONS

  • Is it possible? Can you trust that the order of the list is always the same when saving / restoring, so that the indexes synchronize between the lists?
  • Is this a good way to implement many-to-many relationships with related data?
+6
source share
2 answers

I suspect you are solving the wrong problem. Intermediate merging is a good approach. Your problem is that resumes take a long time to compute; You need to worry more about this;

The preferred approach is to calculate the summary data ahead of time.

In the specific case, "Transaction amounts per person", which means that you want to add an additional field to the Person model and update it with the total amount of all your transactions. You update this at any time when the TransactionPerson is changed, so that the final value will always be correct.

+2
source

1. Yes, you can rely on a supported order. From docs :

when entities are returned by queries and get (), the values ​​of the list properties are in the same order as when they were saved. There is one exception: the values ​​of Blob and Text are moved to the end of the list; however, they retain their original order relative to each other.

2. Yes, ListProperties are your friends to de-normalize relationships. I tend to duplicate data many times and thus use list properties such as "caches" of de-normalized data.

+1
source

Source: https://habr.com/ru/post/894831/


All Articles