[英]Filtering by Foreign Key in Django
We extended Django's User Model with our CompanyRecord model. 我们使用CompanyRecord模型扩展了Django的用户模型。 Every CompanyRecord is a User which all have a profile.
每个CompanyRecord都是一个都有个人资料的User。 When that user logins to system, we can pull it's data in it's CompanyRecord.
当该用户登录系统时,我们可以将其数据提取到CompanyRecord中。
Our Campaign model is related to our CompanyRecord by a foreign key. 我们的Campaign模型通过外键与CompanyRecord相关。 Thus every CompanyRecord has a number of campaigns.
因此,每个CompanyRecord都有许多活动。 I want to take those Campaigns which are related to the CompanyRecord.
我想参加与CompanyRecord相关的活动。 Basically, a CompanyRecord is a User.
基本上,CompanyRecord是用户。 A CompanyRecord has many Campaigns.
CompanyRecord有许多活动。 When a User which is also a CompanyRecord logins to system, I want to get it's associated Campaigns.
当也是CompanyRecord的用户登录系统时,我想获取它的关联Campaign。
In view, I want to take all the campaigns and filter them as, only the Campaigns which are related to our User would show up. 有鉴于此,我想将所有广告系列都进行过滤,因为只有与我们用户相关的广告系列才会显示。
Necessary parts of our data model
#models.py
class CompanyRecord(models.Model):
user = models.OneToOneField(User)
company_id = models.IntegerField(primary_key=True)
company_name = models.CharField(max_length=100)
class Campaign(models.Model):
campaign_id = models.IntegerField(primary_key=True)
company_id = models.ForeignKey(CompanyRecord)
category_id = models.ManyToManyField(Category)
campaign_title = models.CharField(max_length=100)
And the part of view.py
@login_required
def kampanyalar(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
company = request.user.get_profile
userscampaign = Campaign.objects.filter( ###problem### )
content = {'kampanyalar': kampanyalar, 'sirket':sirket}
return render_to_response('kampanyalar.html', content, context_instance=RequestContext(request))
Get all the Campaign
s for a CompanyRecord
by reversing the relationship and using company.campaign_set
: 通过反转关系并使用
company.campaign_set
获取CompanyRecord
的所有Campaign
:
company = request.user.get_profile()
userscampaign = company.campaign_set.all()
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.