这是我的模特
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)
希望我能够通过PagerDutyPolicy& amp; PagerDutyPolicyID并将其作为自己的对象返回,仅使用唯一值
所以例如
Name: bob
PagerDutyPolicyID: 232
PagerDutyPolicy: Team 1
Name: Bill
PagerDutyPolicyID: 232
PagerDutyPolicy: Team 1
Name: Fred
PagerDutyPolicyID: 145
PagerDutyPolicy: Team 2
我需要的是一个只有
的对象PolicyID: 145
Policy: Team 2
PolicyID: 232
Policy: Team 1
在其中,我该怎么做?
由于
答案 0 :(得分:1)
类似的东西:
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]
答案 1 :(得分:1)
你需要两个模型,以及它们之间的外键,例如:
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)
获取所有政策:
PagerDutyPolicy.objects.all()
为bob创建一个新的PagerDuty
对象,在第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)
)
如果您要按policy_name
查找政策,该字段在模型定义中也应该有db_index=True
。
答案 2 :(得分:1)