Use Set of Choices as the order_by - django

class OrganizationAccount(AbstractUser):
OrgRole = [('President', 'President'),('Internal VP', 'Internal Vice President'), ('External VP', 'External Vice President'),
('Treasurer', 'Treasurer'), ('Secretary', 'Secretary'),
("Assistant Secretary", "Assistant Secretary"), ("Auditor", "Auditor"), ("Outreach Program Director", "Outreach Program Director"), ("Event Coordinator", "Event Coordinator"),
("Public Information Officer", "Public Information Officer"), ("Digital Officer", "Digital Officer"), ("Representative", "Representative"), ('Member', 'Member')
]
role = models.CharField(choices = OrgRole, max_length=32)
I'm looking for a way to call
OrganizationAccount.objects.all().order_by('OrgRole')
In a sense that it would produce a query set in this order (Pres, Internal VP, External VP, ...)
Is there any way to execute this?

===== try this (models.py) =======
class OrganizationAccount(models.Model):
OrgRole = [('President', 'President'),('Internal VP', 'Internal Vice President'), ('External VP', 'External Vice President'),
('Treasurer', 'Treasurer'), ('Secretary', 'Secretary'),
("Assistant Secretary", "Assistant Secretary"), ("Auditor", "Auditor"), ("Outreach Program Director", "Outreach Program Director"), ("Event Coordinator", "Event Coordinator"),
("Public Information Officer", "Public Information Officer"), ("Digital Officer", "Digital Officer"), ("Representative", "Representative"), ('Member', 'Member')
]
OrgRole.sort()
role = models.CharField(choices = OrgRole, max_length=32,)
==== Output ======

Related

How to connect jira to power BI service and visualize

I'm using power BI service inside an virtual machine. I want to connect to jira and whatever changes are made on any tickets, I need to capture in my power BI and visualize this.
Is this achievable?
how to achieve the same?
If you need this to Power BI Service, use Dataflow, blank query, and enter this. However, it's gonna work from anywhere. So even Power BI Desktop Power Query.
Change things that are unique for your case such as BaseUrl, JQL or Authentication
let
// Define the connection, JQL
BaseUrl = "https://jira.yoursite.com",
RelativePath = "/rest/api/2/search?",
JQL = "jql=project=XXX",
maxResults = "&maxResults=40",
startAt = "&startAt=",
// Save the records through paging
initialRequest = (Web.Contents(BaseUrl,
[RelativePath = RelativePath&JQL,
// For authorization, generate JIRA token for your profile and place it into parameter called "token", in order to make this work, or simple replace the token with the string
Headers=[Authorization="Bearer "& token]])),
LoadJson = Json.Document(initialRequest),
totalResults = LoadJson[total],
IssuesThroughPaging = List.Generate( () => 0, each _ <= totalResults, each _ + 40,
each
let
Request = (Web.Contents(BaseUrl,
[RelativePath = RelativePath&JQL&maxResults&startAt&Text.From(_),
Headers=[Authorization="Bearer "& token]])),
GetJson = Json.Document(Request),
RetrieveIssues = GetJson[issues]
in
RetrieveIssues
),
// Expand your lists
ExpandResult = List.Combine(List.Combine({IssuesThroughPaging})),
// Expand Key Column
GetKey = (ListOfIssues as list) =>
let
Keys = List.Transform(ListOfIssues, each Record.Field(_, "key"))
in
Keys,
// Expand Fields
GetFields = (ListOfIssues as list) =>
let
Fields = List.Transform(ListOfIssues, each Record.Field(_, "fields"))
in
Fields,
// Call Key and Field functions
AllKeys = GetKey(ExpandResult),
AllFields = GetFields(ExpandResult),
// Put Keys and Fields together
CreateTable = Table.FromColumns({AllKeys, AllFields}, {"key", "Records"}),
// Expand Needed Records
ExpandFields = Table.ExpandRecordColumn(CreateTable, "Records", {"resolution", "lastViewed", "labels", "issuelinks", "assignee", "subtasks", "reporter", "issuetype", "project", "resolutiondate", "updated", "description", "summary", "duedate", "priority", "status", "creator", "created"}, {"resolution", "lastViewed", "labels", "issuelinks", "assignee", "subtasks", "reporter", "issuetype", "project", "resolutiondate", "updated", "description", "summary", "duedate", "priority", "status", "creator", "created"})
in
ExpandFields
The paging is needed because JIRA returns only 50 rows per response, that's why there's function to gather the responses iteratively.
Thank you, Vojtěch.
It works.
Only one error was with "Authorization". But replacing it with "Prefer" fix it.
corrected parameter

Search Suggestions for django elasticsearch

I am using the Django Elasticsearch DSL library in order to integrate django with elasticsearch.
I have the search working properly and I am trying to also add the suggestions feature.
my documents.py is the following
# Name of the Elasticsearch index
INDEX = Index('search_movies')
# See Elasticsearch Indices API reference for available settings
INDEX.settings(
number_of_shards=1,
number_of_replicas=1
)
html_strip = analyzer(
'html_strip',
tokenizer="standard",
filter=["standard", "lowercase", "stop", "snowball"],
char_filter=["html_strip"]
)
#INDEX.doc_type
class MovieDocument(DocType):
"""Movie Elasticsearch document."""
id = fields.IntegerField(attr='id')
title = fields.StringField(
analyzer=html_strip,
fields={
'raw': fields.KeywordField(),
'suggest': fields.CompletionField(),
}
)
summary = fields.StringField(
analyzer=html_strip,
fields={
'raw': fields.KeywordField(),
}
)`
I have added the 'suggest': fields.CompletionField(), as I saw it is required in order to get suggestions for that field.
I am trying then to use something similar as to what is shown here. So in my views.py i have the following
client = Elasticsearch()
search_in_title = 'search term goes here'
sreq = Search().using(client).query("multi_match", query=search_in_title, fields=['title', 'summary'])
ssug = sreq.suggest('title_suggestions', search_in_title, term={'field': 'title'})
but the ssug is always empty, so i am guessing i am using it the wrong way.
You need to reference the title.suggest sub-field instead:
ssug = s.suggest('title_suggestions', search_in_title, term={'field': 'title.suggest'})
^
|
add this

odoo: printing qweb report using wizard

i have two reports cout_materiel_facture_detail_report.xml (detailed report) and cout_materiel_facture_report.xml (simple report) and have a wizard where the user inputs some data and chooses whether he/she wants to print the simple report or the detailed one. Here is the wizard's class:
class CoutMaterielFactureWizard(models.TransientModel):
_name = 'gc.cout_materiel_facture_wizard'
directeur_parc_id = fields.Many2one('hr.employee', string='Directeur Parc')
procedure = fields.Char(string='Procedure')
version = fields.Char(string='Verion')
date_realisation = fields.Date(string='Date realisation')
# is_landscape = fields.Boolean(string='Mode paysage?')
is_detail = fields.Boolean(string='Version simplifiee?')
#api.multi
def do_toggle_print(self):
cout_materiel = self.env['gc.cout_materiel'].browse(self._context.get('active_id', False))
cout_materiel.write({
'directeur_parc_id': self.directeur_parc_id.id
})
# Print the simple report
if not self.is_detail:
return {
'type': 'ir.actions.report.xml',
'name': 'gestion_cout.cout_materiel_facture_report_template',
'report_name': 'gestion_cout.cout_materiel_facture_report_template',
}
# Print the detailed report
else:
sql = "SELECT SUM(h_sup)+SUM(h_exp),SUM(h_im),count(*),SUM(total), famille FROM gc_cout_materiel_line where " \
"cout_materiel_id =%s group by famille "
self.env.cr.execute(sql, (cout_materiel.id,))
results = self.env.cr.fetchall()
if len(results) > 0:
line_ids = []
for nbht, nbhim, qte, prix_total, famille in results:
line_ids.append((0, 0, {
'famille': famille,
'type': 'VA',
'qte': qte,
'nbr_heures': nbht,
'nbr_heures_im': nbhim,
'nbr_jours': 28,
'prix_unitaire': 'VA',
'prix_total': prix_total,
}))
self.env['gc.cout_materiel_facture_temp'].create({
'chantier_name': cout_materiel.chantier_id.name,
'mois_name': cout_materiel.mois_id.name,
'num_annexe': cout_materiel.num_annexe,
'expediteur': cout_materiel.expediteur,
'destinateur': cout_materiel.destinateur,
'application_date': cout_materiel.application_date,
'date_realisation': self.date_realisation,
'directeur_parc_name': self.directeur_parc_id.name,
'procedure': self.procedure,
'version': self.version,
'prix_total_global': cout_materiel.total_global,
'line_ids': line_ids,
})
return {
'type': 'ir.actions.report.xml',
'name': 'gestion_cout.gc_cout_materiel_facture_detail_report_template',
'report_name': 'gestion_cout.gc_cout_materiel_facture_detail_report_template',
}
But i get this error after i hit the print button
I checked out the database and found both reports are present there.
Any help? please!!
Finally i managed to solve my problem!!
Here is what i did:
I created a method in the wizard model which returns a list of objects that i whant to print and linked the wizard to the qweb report.
Then i called the method from the qweb report using object.my_mehtod() in a t-foreach loop, where object represents the wizard.
With this way i am able to create complex reports and print them easily. One can use this method to get data from several tables and organize the data and retur them as a list.
I hope that it will help someone.
Best regards!!

How to POST to server with null Related Resource in TastyPie?

I've got the following two models. They are linked by a OneToOneField relation 'mission' going from the TextMission table to the Mission table.
#Models.py
class Mission(models.Model):
name = models.CharField(max_length = 40)
class TextMission(models.Model):
mission = models.OneToOneField(Mission, related_name="text_mission", primary_key = True)
Sometimes missions will have a corresponding TextMission, but not always. I'm able to get everything working when I'm creating/updating objects in the shell, but TastyPie only handles requests correctly when there IS a TextMission (PUTing to /mission/{id}/). When text_mission=null, it craps out.
My tastypie config:
class MissionResource(ModelResource):
text_mission = fields.ToOneField('path.to.TextMissionResource', attribute='text_mission', related_name='mission', full = True, null = True)
class TextMissionResource(ModelResource):
mission = fields.ToOneField(MissionResource, attribute='mission', related_name='text_mission')
When PUTing the following JSON back to the server (the exact same JSON I received), I get a ValueError:
FAILS
{ "name": "TEST", "id": "1", "text_mission": null, "resource_uri":
"/api/web/mission/1/", }
*** ValueError: Cannot assign None: "Mission.text_mission" does not allow null values.
SUCCEEDS
{ "name": "TEST", "id": "1", "text_mission": {"id": "1", "resource_uri": "/api/web/text_mission/1/"}, "resource_uri":
"/api/web/mission/1/", }
Is there something I'm doing wrong in my code or it just not supposed to work this way. I'm at a loss here.
I'm running TastyPie 0.9.11.
I ended up figuring it out and it was a pretty dumb error. I just needed to add blank = True in addition to null = True:
class MissionResource(ModelResource):
text_mission = fields.ToOneField('path.to.TextMissionResource', attribute='text_mission', related_name='mission', full = True, blank = True, null = True)
That got everything working properly.

Django loaddata: YAML fixtures + GeoDjango MultiPolygon

I am producing a fixture set using pyyaml (among other libraries) which I want to load into my django project with manage.py loaddata. Something is not working with the YAML I am producing (or with GeoDjango, or something else, I suppose) when I run loaddata.
I get this error: Cannot set Neighborhood GeometryProxy (MULTIPOLYGON) with value of type: <type 'list'>
This is a sample of the data I'm trying to load. Below it is the model definition
- fields:
external_id: unincorporated-catalina-island
name: Unincorporated Catalina Island
region: 5
shape:
- - - [-118.604432, 33.47871]
....
- [-118.604375, 33.478642]
- [-118.604325, 33.478558]
- [-118.603603, 33.47794]
model: geo.neighborhood
model:
from django.db import models
from django.contrib.gis.db import models as geo_models
class Area(ABase):
"""
An area defines a geographic area of any size. This abstract class is
subclassed in order to define the type of area being modeled, e.g.
a wide region or a smaller neighborhood.
"""
name = models.CharField(max_length=200)
external_id = models.CharField(max_length=200, blank=True, unique=True,
help_text="The ID of this area in a third party datasource")
shape = geo_models.MultiPolygonField()
def __unicode__(self):
return self.name
class Meta(ABase.Meta):
abstract = True
ordering = ['name']
I presume I'm not formatting the shape field correctly.
The JSON source is here:
I then tried giving the YAML file the whole geometry dict, as below:
- fields:
external_id: lake-los-angeles
name: Lake Los Angeles
region: 2
shape:
coordinates:
- - - [-117.845055, 34.631392]
...
- [-117.845055, 34.631392]
type: MultiPolygon
model: geo.neighborhood
But this produces pretty much the same error as above:
Cannot set Neighborhood GeometryProxy (MULTIPOLYGON) with value of type: <type 'dict'>
to continue the process, I tried the most minimal, hand-crafted version of the YAML file (edited here for brevity by removing a big chunk of the middle coordinates):
- {model: geo.region, fields: {province: 1, id: &angeles-forest 1,
name: Angeles Forest, external_id: angeles-forest, shape: [ [ [ [ -118.298947, 34.157699 ], [ -118.298830, 34.157683 ], [ -118.298638, 34.157808 ], [ -118.298481, 34.157914 ], [ -118.298172, 34.158122 ], [ -118.297935, 34.158293 ], [ -118.297878, 34.158342 ], [ -118.297854, 34.158477 ], [ -118.297837, 34.158577 ], [ -118.297744, 34.158575 ], [ -118.299082, 34.157728 ], [ -118.298947, 34.157699 ] ] ] ]}}
This produces the same error as above, complaining about <type 'list'>
What should the YAML file's multipolygon (here, 'shape') field look like for loaddata to accept it?
GEOS is looking for WKT (Well Known Text) format, which is close to, but not the same as, the geoJSON/YAML format above.
The practical solution was to use geomet to transform the JSON input into WKT, which could then comfortably reside within the YAML file... fun with brackets varieties!
So then the successful format looks like this:
- fields: {external_id: toluca-lake, name: Toluca Lake, region: 9, shape: 'MULTIPOLYGON
(((-118.357158 34.164806, -118.357154 34.163097, -118.357151 34.161287, -118.356036
34.161287, -118.354978 34.161288, -118.354682 34.161288, -118.354020 34.161288,
-118.353103 34.161289, -118.353034 34.161128, -118.352925 34.160873, -118.352156
34.159076, -118.352138 34.159033, -118.351812 34.158271, -118.351554 34.157668,
-118.351235 34.156925, -118.350751 34.155794, -118.350196 34.154497, -118.349988
34.154012, -118.349958 34.153941, -118.349830 34.153812, -118.349756 34.153629,
-118.349673 34.153425, -118.349643 34.153350, -118.349664 34.153256, -118.349216
34.152209, -118.348450 34.150419, -118.348067 34.149523, -118.347680 34.148618,
-118.347555 34.148327, -118.347308 34.147748, -118.346800 34.146562, -118.346767
34.146485, -118.346624 34.146151, -118.346446 34.145735, -118.346430 34.145696,
-118.345949 34.144573, -118.345903 34.144218, -118.345691 34.142572, -118.345678
34.142466, -118.345665 34.142367, -118.345665 34.142367, -118.345698 34.142356,
-118.346425 34.142207, -118.346907 34.142174, -118.347168 34.142177, -118.347168
34.142177, -118.347522 34.142180, -118.348435 34.142262, -118.351608 34.142887,
-118.352051 34.142964, -118.354160 34.143211, -118.354603 34.143227, -118.357641
34.143337, -118.357783 34.143342, -118.357967 34.143348, -118.358339 34.143269,
-118.358930 34.143143, -118.359082 34.143111, -118.359198 34.143088, -118.361136
34.142712, -118.361258 34.142688, -118.361267 34.142686, -118.361264 34.142680,
-118.361340 34.142669, -118.361411 34.142907, -118.361711 34.143307, -118.362211
34.144107, -118.362911 34.145107, -118.363350 34.145900, -118.363863 34.146805,
-118.364611 34.148106, -118.365011 34.148806, -118.365312 34.149206, -118.365512
34.149606, -118.366012 34.150406, -118.366612 34.151206, -118.367112 34.152206,
-118.367609 34.153023, -118.367885 34.153506, -118.368500 34.154522, -118.368612
34.154706, -118.369145 34.155691, -118.369652 34.156644, -118.370237 34.157613,
-118.369112 34.157606, -118.368112 34.157606, -118.367012 34.157606, -118.365929
34.157604, -118.364912 34.157606, -118.363793 34.157613, -118.362712 34.157606,
-118.361601 34.157613, -118.361623 34.159427, -118.361612 34.161206, -118.361612
34.163106, -118.361612 34.164806, -118.360512 34.164806, -118.359412 34.164806,
-118.358211 34.164806, -118.357211 34.164806, -118.357158 34.164806)))'}
model: geo.neighborhood