To preface, I come from a SQL background.
I have these two models;
Class EventType(models.Model):
event_type_id = models.AutoField(primary_key = True)
event_type = models.CharField(max_length=10)
event_priority = models.IntegerField()
class Meta:
managed = True
db_table = 'app_event_type'
class Event(models.Model):
event_id = models.AutoField(primary_key = True)
event_name = models.CharField(max_length=25)
event_type = models.ForeignKey(EventType, on_delete=models.CASCADE)
is_active = models.BooleanField(default=False)
class Meta:
managed = True
db_table = 'app_event'
I’ve been playing around in the Shell to see what I can do.
Here is one test. This is really cool because oyu can filter using criteria from each model together.
>>> from app_test.models import *
>>> ee = EventType.objects.get(event_type_id=1).event_set.all()
<QuerySet [<Event: Event object (2)>, <Event: Event object (3)>]>
>>>
But I am not understanding the practicality / purpose. I am not saying there isn’t one / any - I am saying I don’t see it and am hoping someone can shed some light.
I assume you’re supposed to add something like this to the end of your Model classes. That way it actually returns something useful rather than IDs.
def __str__(self):
# return {self.event_name}
But what would you use these for? I guess when I need to return the type of something this makes it easy for me, but I feel like that is super limited. Which makes me feel like I am missing something pretty major.
What are some common use cases for these relationships / reverse relationships? Is it simply a way to join data with no work on our part? Meaning, django just handles the JOINs for us and then we architect our app to utilize that the best way possible to meet our needs, or are their some intended use cases?
Thanks.