I have the following query which works perfectly:
campaignFixtures = UserSelection.objects.select_related().filter(user=currentUserID,campaignno=currentCampaignNo).order_by('fixtureid__fixturedate')[:1]
However, I need to filter a field from another table as follows:
campaignFixtures = UserSelection.objects.select_related().filter(user=currentUserID,campaignno=currentCampaignNo,straightredfixture__fixturematchday=18).order_by('fixtureid__fixturedate')[:1]
But, I am receiving the following error:
Cannot resolve keyword 'straightredfixture' into field. Choices are: campaignno, fixtureid, fixtureid_id, teamselection1or2, teamselectionid, teamselectionid_id, user, user_id, userselectionid
The models are as follows:
class StraightredFixture(models.Model):
fixtureid = models.IntegerField(primary_key=True)
home_team = models.ForeignKey('straightred.StraightredTeam', db_column='hometeamid', related_name='home_fixtures')
away_team = models.ForeignKey('straightred.StraightredTeam', db_column='awayteamid', related_name='away_fixtures')
fixturedate = models.DateTimeField(null=True)
fixturestatus = models.CharField(max_length=24,null=True)
fixturematchday = models.ForeignKey('straightred.StraightredFixtureMatchday', db_column='fixturematchday')
spectators = models.IntegerField(null=True)
hometeamscore = models.IntegerField(null=True)
awayteamscore = models.IntegerField(null=True)
homegoaldetails = models.TextField(null=True)
awaygoaldetails = models.TextField(null=True)
hometeamyellowcarddetails = models.TextField(null=True)
awayteamyellowcarddetails = models.TextField(null=True)
hometeamredcarddetails = models.TextField(null=True)
awayteamredcarddetails = models.TextField(null=True)
soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_season')
def __unicode__(self):
return self.fixtureid
class Meta:
managed = True
db_table = 'straightred_fixture'
class UserSelection(models.Model):
userselectionid = models.AutoField(primary_key=True)
campaignno = models.CharField(max_length=36,unique=False)
user = models.ForeignKey(User, related_name='selectionUser')
teamselection1or2 = models.PositiveSmallIntegerField()
teamselectionid = models.ForeignKey('straightred.StraightredTeam', db_column='teamselectionid', related_name='teamID')
fixtureid = models.ForeignKey('straightred.StraightredFixture', db_column='fixtureid')
class Meta:
managed = True
db_table = 'straightred_userselection'
Any help would be appreciated, Alan.
I don't think the problem is related to selected_related. You are just trying to filter using a wrong lookup value. How about filtering with fixtureid__fixturematchday instead:
UserSelection.objects.select_related().filter(user=currentUserID, campaignno=currentCampaignNo, fixtureid__fixturematchday=18).order_by('fixtureid__fixturedate')[:1]
Since you want to get only a single object, why don't you just use .first() to get an object instead of a queryset with one item:
campaignFixture = UserSelection.objects.select_related("fixtureid").filter(...).order_by(...).first()
According to your model, the relationship is the fixtureid
UserSelection.objects.select_related().filter(user=currentUserID,campaignno=currentCampaignNo,fixtureid__fixturematchday=18)
Related
I have 3 models
class QuestionsModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
Question = models.CharField(max_length=200)
class AnswersModel(models.Model):
Question = models.ForeignKey(QuestionsModel, related_name='QuestionAnswer')
Answer = models.CharField(max_length=200)
class UsersAnswerModel(models.Model):
Answer = models.ForeignKey(AnswersModel, related_name='UsersAnswer')
RegistrationID = models.CharField(max_length=200)
I am trying to Count How many UsersAnswer the Question
what I tried :
class DashboardAdmin(admin.ModelAdmin):
class Meta:
model = QuestionsModel
change_list_template = 'admin/Dashboard_change_list.html'
date_hierarchy = 'created'
def has_add_permission(self, request):
return False
def changelist_view(self, request, extra_context=None):
response = super().changelist_view(
request,
extra_context=extra_context,
)
try:
qs = response.context_data['cl'].queryset
except (AttributeError, KeyError):
return response
metrics = {
'totalAnswers' : models.Count('QuestionAnswer'),
'totalUsersAnswer' : models.Count(UsersAnswer=OuterRef('QuestionAnswer'))
}
response.context_data['summary'] = list(
qs
.values('Question')
.annotate(**metrics)
.order_by('-totalUsersAnswer')
)
return response
admin.site.register(DashboardModel, DashboardAdmin)
I could not solve
'totalUsersAnswer' : models.Count(UsersAnswer=OuterRef('QuestionAnswer'))
how to count nested foreign key
any help please
class AnswersModel(models.Model):
Question = models.ForeignKey(QuestionsModel, related_name='QuestionAnswer')
Answer = models.CharField(max_length=200)
class UsersAnswerModel(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT)
Answer = models.ForeignKey(AnswersModel, related_name='UsersAnswer')
RegistrationID = models.CharField(max_length=200)
Q- How many users answer a Question?
e.g
user_answer = UsersAnswerModel.objects.filter(Answer__question__id=2).count()
You can now annotate based on your need.
Your models need to be renamed
AnswersModel to simply Answer
UsersAnswerModel to UserAnswer and there should be a user entity as a field as I have done above.
3.Fieldnames in model is better lowercased.
I have Solve it by add QuestionAnswer__UsersAnswer
metrics = {
'totalAnswers' : models.Count('QuestionAnswer', distinct=True),
'totalUsersAnswer' : models.Count('QuestionAnswer__UsersAnswer'),
}
I am trying to log the changes on a One2many field using track_visibility='onchange'. But it's not working.
Here is the code:
respartner.py
bank_account_ids = fields.One2many('customer.bank.account','partner_id',
string='Account',track_visibility="onchange")
account.py
_name = 'customer.bank.account'
_description = 'Partner Bank Account Details'
partner_id = fields.Many2one('res.partner',string="Partner")
name = fields.Integer(string="Account Number",required=True,
track_visibility="onchange")
bank_id = fields.Many2one('partner.bank',string="Bank",track_visibility="onchange")
branch_id = fields.Many2one('partner.bank.branch',string="Branch",
track_visibility="onchange")
Yes, No need to touch ORM. Try this
class ParentClass(models.Model):
_name = 'parent.class'
_inherit = ['mail.thread']
child_ids = fields.One2many('child.class', 'relational_field_name_id')
class ChildClass(models.Model):
_name = 'child.class'
_inherit = ['mail.thread']
name = fields.Char(tracking=True) # Note that tracking is true here
relational_field_name_id = fields.Many2one('parent.class')
def write(self, vals):
super().write(vals)
if set(vals) & set(self._get_tracked_fields()):
self._track_changes(self.relational_field_name_id)
def _track_changes(self, field_to_track):
if self.message_ids:
message_id = field_to_track.message_post(body=f'<strong>{ self._description }:</strong> { self.display_name }').id
trackings = self.env['mail.tracking.value'].sudo().search([('mail_message_id', '=', self.message_ids[0].id)])
for tracking in trackings:
tracking.copy({'mail_message_id': message_id})
If you just want to track on relational and not current model then use write instead of copy method
tracking.write({'mail_message_id': message_id})
And for delete and create you can just use message_post inside create and unlink method
self.message_post(body=f'<strong>{ self._description }:</strong> { self.display_name } created/deleted')
I have tried to think about how the following SQL query would be structured as a Django ORM query but I have had no luck in my multiple attempts. Can anyone help?
SELECT targets_genetarget.gene, count(targets_targetprediction.gene) as total
FROM targets_genetarget
LEFT OUTER JOIN targets_targetprediction on targets_targetprediction.gene =
targets_genetarget.gene
WHERE list_name LIKE %s
GROUP BY targets_genetarget.gene
class GeneTarget(models.Model):
list_name = models.CharField(max_length=100)
gene = models.CharField(max_length=50)
date_added = models.DateField(auto_now=True)
class Meta:
unique_together = (('list_name', 'gene'),)
def __str__(self):
return self.list_name
class TargetPrediction(models.Model):
specimen_id = models.CharField(max_length=100)
patient_peptide = models.ForeignKey(Peptide, on_delete=models.CASCADE, verbose_name="Peptide", related_name="predictions")
allele = models.ForeignKey(Allele, on_delete=models.CASCADE, verbose_name="Allele", related_name="predictions")
gene = models.CharField(max_length=50)
class Meta:
unique_together = (('specimen_id', 'patient_peptide', 'allele', 'gene'),)
def get_absolute_url(self):
return f'/samples/specid-{self.specimen_id}'
def __str__(self):
return (f'Specimen: {self.specimen_id} Peptide: {self.patient_peptide} Allele: {self.allele} Gene: {self.gene} ')
There's nothing stopping you declaring the TargetPrediction.gene field as a foreign key using the to_field attribute, so you wouldn't need to change the data at all:
class TargetPrediction(models.Model):
...
gene = models.ForeignKey("GeneTarget", to_field="gene")
Now your query simply becomes:
GeneTarget.objects.filter(list_name="whatever").values("gene").annotate(total=Count("targetprediction"))
I have two tables
class student(models.Model):
frist_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
class subject(models.Model):
student = models.ForeignKey(student)
sub_name = models.CharField()
I want student list and subject count in serializer
my serializer
classs SubjectSerializers(serializers.ModelSerializer):
class Meta:
model = JobPosting
fields = ('id','sub_name')
class StudentSerializers(serializers.ModelSerializer):
sub = SubjectSerializers(source = 'student')
class Meta:
model = JobPosting
fields = ('id','first_name', 'last_name','sub')
How can i get subject count for every student in serializer, Now i am geting subject table data but i want count like this
"detail": [{
"id": 680,
"first_name": "riya",
"last_name": "tri",
"subject_count": 5
}],
You can achieve this by using a serializer method field
Then StudentSerializer becomes the following:
class StudentSerializers(serializers.ModelSerializer):
sub = SubjectSerializers(source = 'student')
subject_count = serializers.SerializerMethodField()
class Meta:
model = JobPosting
fields = ('id','first_name', 'last_name','sub')
def get_subject_count(self, student):
return Subject.objects.filter(student=student).count()
I have the following code in a view to get some of the information on the account to display. I tried for hours to get this to work via ORM but couldn't make it work. I ended up doing it in raw SQL but what I want isn't very complex. I'm certain it's possible to do with ORM.
In the end, I just want to populate the dictionary accountDetails from a couple of tables.
cursor.execute("SELECT a.hostname, a.distro, b.location FROM xenpanel_subscription a, xenpanel_hardwarenode b WHERE a.node_id = b.id AND customer_id = %s", [request.user.id])
accountDetails = {
'username': request.user.username,
'hostname': [],
'distro': [],
'location': [],
}
for row in cursor.fetchall():
accountDetails['hostname'].append(row[0])
accountDetails['distro'].append(row[1])
accountDetails['location'].append(row[2])
return render_to_response('account.html', accountDetails, context_instance=RequestContext(request))
It would be easier if you post models. But from SQL I'm assuming the models are like this:
class XenPanelSubscription(models.Model):
hostname = models.CharField()
distro = models.CharField()
node = models.ForeignKey(XenPanelHardwareNode)
customer_id = models.IntegerField()
class Meta:
db_table = u'xenpanel_subscription'
class XenPanelHardwareNode(models.Model):
location = models.CharField()
class Meta:
db_table = u'xenpanel_hardwarenode'
Based on these models:
accountDetails = XenPanelSubscription.objects.filter(customer_id = request.user.id)
for accountDetail in accountDetails:
print accountDetail.hostname, accountDetail.distro, accountDetail.node.location