Reputation: 2587
this is my model
class pdUser(models.Model):
Name = models.CharField(max_length=200)
Mobile = models.CharField(max_length=200)
PagerDutyID = models.CharField(max_length=200)
PagerDutyPolicyID = models.CharField(max_length=200)
PagerDutyPolicy = models.CharField(max_length=200)
Want i want to be able to do is group by PagerDutyPolicy & PagerDutyPolicyID and return that as an object of its own with unique values only
so for example
Name: bob
PagerDutyPolicyID: 232
PagerDutyPolicy: Team 1
Name: Bill
PagerDutyPolicyID: 232
PagerDutyPolicy: Team 1
Name: Fred
PagerDutyPolicyID: 145
PagerDutyPolicy: Team 2
what i need is an object that has only got
PolicyID: 145
Policy: Team 2
PolicyID: 232
Policy: Team 1
in it, how would i do this?
Thanks
Upvotes: 1
Views: 3458
Reputation: 2496
You can combine values and distinct methods like this:
pdUser.objects.all().values("PagerDutyPolicyID", "PagerDutyPolicy").distinct()
However this will produce fields with PagerDutyPolicyID
, PagerDutyPolicy
names
Upvotes: 1
Reputation: 27321
You'll need two models, and a foreign key between them, e.g.:
from django.contrib.auth.models import User
class PagerDutyPolicy(models.Model):
# the model automatically gets an id field
policy_name = models.CharField(max_length=200)
class PagerDuty(models.Model):
# I'm assuming you wanted these to be related to users who can log in..
user = models.ForeignKey(User)
mobile = models.CharField(max_length=200)
policy = models.ForeignKey(PagerDutyPolicy)
To get all policies:
PagerDutyPolicy.objects.all()
To create a new PagerDuty
object for bob, butting him in Team 1:
PagerDuty.objects.create(
user=User.objects.get(username='bob'), # or create a new user
mobile='...',
# policy=PagerDutyPolicy.objects.get(policy_name='Team 1') # or..
policy=PagerDutyPolicy.objects.get(id=232)
)
if you're going to look up policies by policy_name
that field should also have a db_index=True
in the model definition.
Upvotes: 1
Reputation: 15170
something like this:
id_teams = pdUser.objects.values_list('id', 'team', flat=True)
id_teams = set(id_teams)
import collections
IDTeam = collections.namedtuple('IDTeam', ['id', 'team'])
output = [IDTeam(id=id, team=team)
for id,team in id_teams]
Upvotes: 1