Search code examples
databasedjangomodelsdjango-queryset

Django database fields for better queries


Hello I would like to ask a question for setting up some fields in my db. I have three models

models

class Customer(models.Model):
    #fields


class Entry(models.Model):
    #fields
    customer = models.ForeignKey(Customer, related_name='entries')


class EntryHistory(models.Model):
    #fields
    entry = models.OneToOne(Entry, related_name='history')

I want to get all Entry histories for a specific customer. Isn't that

for entry in customer.entries:
    try:
        history.append(entry.history)
    except entry.history.related.models.DoesNotExist:
        pass(or continue?)

My thought search all customers entries and if they have a history added to the list. Would it be better if i just added a customer field in the EntryHistory?Would the query be quicker? This would be a frequent transaction in my project. But i know adding a customer in the EntryHistory model is redundant since I know who the customer is from the entry field. Should I be worried if e.g i have a lot of customers and a lot of entries for each?


Solution

  • I want to get all Entry histories for a specific customer.

    customer = Customer.objects.get(pk=1)
    EntryHistory.objects.filter(entry__customer=customer)
    

    Django provides both forward and reverse lookups for foreign keys, so exploiting that you can go from EntryHistory -> Entry -> Customer