[Answered ]-Understanding Querysets, creating the perfect database relationship

2👍

According to your question, you have something like this:

 class User(models.Model):
      pass

 class Campaign(models.Model):
      user = models.ForeignKey(User, verbose_name="Attached to")
      message = models.CharField()
      destination = models.CharField()

 class Beacon(models.Model):
      factory_id = models.CharField()
      campaign = models.ForeignKey(Campaign, verbose_name="Campaign")

You can follow ForeignKey “backward”, by using campaign_set generated attribute:

If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased.

So you can query your Beacon model like this:

beacon = Beacon.objects.get(factory_id="XXXX-YYYYY")
# Get every campaigns related and only relevant fields (in a list of dict)
campaigns = beacon.campaign_set.all().values('message', 'destination')

for campaign in campaigns:
    print(campaign['message'])
    print(campaign['destination'])

For your dictionary, it is impossible to make it exactly like this. You can’t have a duplicate key.

0👍

I wish to return all Beacons that relate to the User whilst also getting the data for Campaign

beacons = Beacon.objects.filter(campaign__user=user).select_related('campaign')

You can then easily process this into your desired data structure.

I’m thinking Querysets here, but I’ve never worked with them before and it just confused me

A QuerySet is simply how the Django ORM represents a query to your database that results in a set of items. So the above is a QuerySet, as is something as simple as User.objects.all(). You can read some introductory material about QuerySets in the documentation.

Leave a comment