Is it possible to do an update or create where a field beginswith? or like?
I want to update or create a record that begins with a certain string, but everything after the string could be different
For example:
notes_data = 'DB1223 - blah blah, stats : 342, bad : 311'
notes_obj, record = Notes.objects.update_or_create(
defaults={
'notes' : notes_data,
},
'notes' : notes_data.beginswith('DB1223'),
)
You can use __startswith with update_or_create:
notes_obj, created = Notes.objects.update_or_create(
defaults={
'notes': notes_data,
},
notes__startwith='DB1223',
)
Related
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
I have a WTForm that submits its data in JSON format. Say the database is one recipe to many recipe steps.
{
"stepset-0": {
"recipe_step_id": "5",
"recipe_step_name": "step 1",
"recipe_step_temp": "666.0"
},
"stepset-1": {
"recipe_step_id": "6",
"recipe_step_name": "Step 2",
"recipe_step_temp": "57.0"
},
"stepset-2": {
"recipe_step_id": "7",
"recipe_step_name": "Step 3",
"recipe_step_temp": "68.0"
},
"stepset-3": {
"recipe_step_id": "8",
"recipe_step_name": "Step 4",
"recipe_step_temp": "73.0"
}
}
I'm using JS to remove elements from the table, but currently trying to get my head round how to update the data in the recipe_steps table.
The logic should be basically:
Find the steps in the step table that match the recipe.
See if those steps are in the JSON data (match using the id)
Delete anything that isn't in the submitted JSON.
So if I remove the row with recipe_step_id '8', this gets submitted to the route, and the route works out that it isn't in the data, removes it from the db, then processes the rest of the data as per the route.
My current route (showing add/update functions) is thus:
#app.route('/recipe/recipesteps/<int:recipe_id>/update', methods=['GET', 'POST'])
#login_required
def updaterecipesteps(recipe_id):
recipe = Recipe.query.get_or_404(recipe_id)
data = request.form
nested_data = nest_once(data)
for key, val in nested_data.items():
recipe_step_id = val['recipe_step_id']
recipe_step_temp = val['recipe_step_temp']
recipe_step_name = val['recipe_step_name']
recipe_id = recipe
if recipe_step_id:
recipe_step = ReciperecipeSteps.query.get_or_404(recipe_step_id)
recipe_step.name = recipe_step_name
recipe_step.step_temp = recipe_step_temp
db.session.commit()
else:
recipe_step = ReciperecipeSteps(name=recipe_step_name,
step_temp=recipe_step_temp,
recipe_id=recipe_step.recipe_id)
db.session.add(recipe_step)
db.session.commit()
return redirect(url_for('recipe', recipe_id=recipe.id))
The closest I've got to this is this query:
mash_steps = RecipeSteps.query.filter(RecipeSteps.id.not_in([nested_data.recipe_step_id for val in nested_data.items]), RecipeSteps.recipe_id == recipe_id).all()
...but Python won't iterate over the object.
Probably far from the best way of doing this (I'd imagine I could have parsed the JSON data in the query), but this is what I got working:
# Build a list from the step ids
step_id = []
for key, value in nested_data.items():
recipe_step_id = value['recipe_step_id']
step_id.append(recipe_step_id)
# Query matching items that aren't on the list
recipe_steps = RecipeSteps.query.filter(RecipeSteps.id.not_in(step_id), RecipeSteps.recipe_id == recipe.id).all()
# Loop through the results and delete
for m in recipe_steps:
db.session.delete(m)
db.session.commit()
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
This is my function. I am able to create a new quatation on clicking a button in my indent form and also able to see the indent sequence in quatation. But I am not able to update product line in indent in purchase order line. Can any1 help me out here..?
#api.multi
def action_rfq(self):
rfq_obj = self.env['purchase.order']
for order in self.product_lines:
rfq_id = rfq_obj.create({
'series': self.name,
'order_line': ({
'product_id': order.product_id.id,
'name': order.name,
'product_qty': order.product_uom_qty,
'product_uom': order.product_uom.id,
'price_unit': order.price_unit,
'date_planned': datetime.now(),
'order_id': order.indent_id.id,
})
})
'product_id': order.product_id.id,
'name': order.name,
'product_qty': order.product_uom_qty,
'product_uom': order.product_uom.id,
'price_unit': order.price_unit,
'date_planned': datetime.now(),
'order_id': order.indent_id.id,
})
})
return rfq_id
Hello Gautam,
It would be late now ,but can be helpfull for others.You want to update product line in indent in purchase order line ...so for updating the order line you have to call the write function and pass the product value like this...
order_line_obj = self.env['purchase.order.line']
first create the obj of purchase .order.line
browse_obj=order_line_obj.browse(int(active_id))
After creating the object call browse object and pass the id of present record
order_line_id=browse_obj.write({'name':hotel_name})
After doing this call the write function with browse object.and doing so your record will be updated.
I have two entities (there is no relation between the two entities): A: Relation and B: Post.
I get every post from the current user to display them on the homepage with this request:
public function getPostsCurrentUser($currentUser)
{
$qb = $this->createQueryBuilder('p');
$qb->where('p.member = :member')
->setParameters(['member' => $currentUser])
->orderBy('p.created', 'DESC');
return $qb->getQuery()->getResult();
}
In the example "A: Relation" the user 2 follow the user 1. When a user follow an other user, I would like to also display on the homepage every post of users that the current user are following.
I don't see how to create this request. Can anybody help me ?
Thanks
In the sense of http://sqlfiddle.com/#!9/c5a0bf/2, I would suggest something like the following which uses a subquery to select the ids of all followed users:
class PostRepository {
public function getPostsOfUser($id) {
$query = $this->getEntityManager()->createQuery(
"SELECT p.content
FROM AppBundle:Post p
WHERE p.member = :id
OR p.memberId IN (
SELECT r.friend
FROM AppBundle:Relation r
WHERE r.user = :id
)
ORDER BY p.created DESC"
);
return $query->setParameter('id', $id)
->getResult();
}
}