Home > Mobile >  Merge Django models into a view
Merge Django models into a view

Time:01-12

I am attempting to merge and pull data from three Django models into a view. Players and Events relate to each other in the Details model (a player can attend many events) using models.ForeignKey.

In other platforms I would have written a DB View to join tables and the application would query that view.

From what I understand Django does not support data views within Models.

Looking for help on how I would approach this in Django.

class Players(models.Model):
  firstName = models.CharField(max_length=255)
  lastName = models.CharField(max_length=255)
  highSchool = models.CharField(max_length=255)
  gradYear = models.IntegerField()
  slug = models.SlugField(default="", null=False)

class Events(models.Model):
  title = models.CharField(max_length=255)
  location = models.CharField(max_length=255)
  date = models.DateField()

class Details(models.Model):
  event = models.ForeignKey(Events, on_delete=models.CASCADE)
  player = models.ForeignKey(Players, on_delete=models.CASCADE)
  height = models.IntegerField(default=None, blank=True)
  weight = models.IntegerField(default=None, blank=True)



def playerdetail(request,slug):
    playerinfo = Details.objects.get(id=1)
    template = loader.get_template('playerdetail.html')
    context = {
        'playerinfo': playerinfo,
    }
    return HttpResponse(template.render(context, request))

CodePudding user response:

You are actually doing what you needed to do with the code you provided. When you are invoking a query on a model that connects those two entities (Players,Events), it performs the join when you try to access each of these properties through the foreign key fields.

For example, for accessing the player information (which makes the Django ORM perform the join operation in the background):

# Get the first name of the player
first_name = playerinfo.player.firstName

For filtering and showing in other places, you can use the notation field__subfield

For more information, please read the examples of this website: https://books.agiliq.com/projects/django-orm-cookbook/en/latest/index.html

  • Related