im trying to run this python-django code below, but am getting a blank output
SitePaths = PathsOfDomain.objects.filter(pathToScan__contains="www.myapp.com")
return SitePaths
PathsOfDomain is the object representation of a db table.
I'm trying to iterate through a db field name pathToScan and output each value
If someone can please shed some light on this.
Thank you.
If you meant to query for matching PathsOfDomain rows in the database, use the .objects attribute to create a query set:
SitePaths = PathsOfDomain.objects.filter(FKtoTld__id=domain_in_session)
See Making queries in the Django documentation.
Alternatively, if there is a foreign key relationship between the Tld and PathsOfDomain objects, use the related objects manager instead:
SitePaths = domain_in_session.pathsofdomain_set.all()
Related
My Django application has a backend postgres database with a tsvector column that whose values are already computed and indexed. I want to use Django's ORM to do a full text search over that column with a query that would look something like this:
SELECT [fields] FROM [table] WHERE tsvector_column ## plainto_tsquery('TEXT HERE');
The problem I am running into is, when I use annotate and SearchVector, Django seems to re-to_tsvector over the tsvector column, resulting in an error.
This is what I am doing:
Posts.objects.annotate(search=SearchVector('THE_TS_VECTOR_COLUMN'),).filter(search='SEARCH TEXT')
How would one do this in Django?
Thanks!
Figured it out!
I used inspectdb to create the database model, so it guessed that the type was a TextField. I changed it to a SearchVectorField as follows:
from django.contrib.postgres.search import SearchVectorField
class CLASSNAME(models.Model):
THE_TS_VECTOR_COLUMN = SearchVectorField(null=True)
Then I updated the query to this:
query = SearchQuery("TEXT TO SEARCH")
CLASSNAME.objects.annotate(rank=SearchVector(F('THE_TS_VECTOR_COLUMN'), query))
The resulting query was this:
SELECT [ALL FIELD VALUES] FROM "CLASSNAME" WHERE "CLASSNAME"."THE_TS_VECTOR_COLUMN" ## (plainto_tsquery(TEXT TO SEARCH)) = true
And that's exactly what I wanted. Great!
it is my first time to use mongoengine, I know the ORM concept.
I want to know may I get the data in one DB and using the same object to store in another DB??
class User(Document):
email = EmailField(required=True, unique= True)
salary = IntField(require=True)
connect(alias='default',db='tumblelog')
connect(alias='testdb',db='testdb')
users = User.objects
with switch_db(User,'testdb') as User:
for user in users:
User(email=user.email,salary=user.email).save # it works
user.save() #doesn't works
I've found out that by using ORM to get a data from one DB, it will create an object unique to the DB you get it from. You won't be able to use the same object to store it into another DB.
What I would suggest is that you initialise an empty object, for example User, for the other DB and fill it with values from the original object and then store it.
You might want to have a look at this question. Sequelize: Using Multiple Databases
I am trying to query my postgres database from django, the query I'm using is
s = Booking.objects.all().filter(modified_at__range=[last_run, current_time], coupon_code__in=l)
Now I am changing this object of mine in some ways in my script, and not saving it to the database. What I want to know is that, is it possible to query this object now?
say, I changed my variable as
s.modified_at = '2016-02-22'
Is it still possible to query this object as:
s.objects.all()
or something similar?
The QueryManager is Django's interface to the database (ORM). By definition this means you can only query data that has been stored in the database.
So, in short: "no". You cannot do queries on unsaved data.
Thinking about why you are even asking this, especially looking at the example using "modified_at": why do you not want to save your data?
(You might want to use auto_now=True for your "modified_at" field, btw.)
You could do something like this:
bookings = Booking.objects.all().filter(modified_at__range=[last_run, current_time], coupon_code__in=l)
for booking in bookings:
booking.modified_at = 'some value'
booking.save() # now booking object will have the updated value
I have a model with the a datetime field
user_since = db.DateTimeField()
When I try to insert a new object of the model into mongo, There is no error. But the write does not succeed.
I printed the object from to_json() and tried to insert it with mongo shell, I get the following error.
field names cannot start with $ [$date] at src/mongo/shell/collection.js:L147
the to_json had this field.
"user_since": {"$date": 1392205572989}
I can't seem to find any pointers on how to solve this.
What is causing the write to fail?
How can I make mongoengine to throw error in case of write failure.? Or at least find out what the error was?
Thanks.
Update:
As I found later the real problem is not the datetime field. The details of the problem are in this question MongoEngine Document Object made using from_json doesn't save
With MongoDB you cannot have '$' at the beginning of the field name.
MongoDB Limits and Thresholds - Restrictions on Field Names:
Field names cannot contain dots (i.e. .), dollar signs (i.e. $), or
null characters. See Dollar Sign Operator Escaping for an alternate
approach.
Try to name it differently.
edit:
According to MongoEngine documentation, you could pass db_name parameter:
db_field – The database field to store this field in (defaults to the
name of the field)
I am trying to use a Django model to for a record but then return a concatenated field of two different tables joined by a foreign key.
I can do it in SQL like this:
SELECT
location.location_geoname_id as id,
CONCAT_WS(', ', location.location_name, region.region_name, country.country_name) AS 'text'
FROM
geonames_location as location
JOIN
geonames_region as region
ON
location.region_geoname_id = region.region_geoname_id
JOIN
geonames_country as country
ON
region.country_geoname_id = country.country_geoname_id
WHERE
location.location_name like 'location'
ORDER BY
location.location_name, region.region_name, country.country_name
LIMIT 10;
Is there a cleaner way to do this using Django models? Or do I need to just use SQL for this one?
Thank you
Do you really need the SQL to return the concatenated field? Why not query the models in the usual way (with select_related()) and then concatenate in Python? Or if you're worried about querying more columns than you need, use values_list:
locations = Location.objects.values_list(
'location_name', 'region__region_name', 'country__country_name')
location_texts = [','.join(l) for l in locations]
You can also write raw query for this in your code like that and later on you can concatenate.
Example:
org = Organization.objects.raw('SELECT organization_id, name FROM organization where is_active=1 ORDER BY name')
Keep one thing in a raw query you have to always fetch primary key of table, it's mandatory. Here organization_id is a primary key of contact_organization table.
And it's depend on you which one is useful and simple(raw query or model query).