Partial Query of a django JSONField - python

I have a model with a django JSONField. The JSONField has a key called 'name'. I want to search across my model, for users whose names contain Foo; something like :
User.objects.filter(jsonfield['name']__icontains='foo')
As far as I have researched there is no easy way to do this. My next alternative is to add a new column for jsonfield['name'] so I can search it. Although the fix I am looking for needs to be quick, I am also open to know my more involved options so I can refactor later. Thank you.

Related

how to do migrations dynamically in django?

Is there any way that we can create an create an input field dynamically in the form without doing manually work, like first create the particular field in model and then run makemigartions command and then run migrate command.
I have tried using formset but that is not what i am looking for.
refer to vtiger demo
username - admin
password - admin
when you open this link there is a option ADD CUSTOM FIELD. i want to do same with my django. Hope i am able to explain you what i wants to do. I am searching for this since 3 days and cannot able to implement that.
You DO NOT (I repeat: "you DO NOT") want to "dynamically add fields" to a model (that is, to your database schema). You want your database schema to be stable, known, and totally under version control. If you don't get why, just ask yourself how your code could use a field that it's not even aware of (and that's only one of the oh so many reasons not to do such a thing).
"Features" like the one you mention are built using a fixed schema that is used to describe a "meta schema", where each "custom field" is actually a record in a "custom_fields" table, and then you usually have yet another table to store the matching values. This doesn't come without a lot of code complexity and a huge impact on performances both at the code AND database level.
If this is a project requirement, you now at least have a first idea of how this is to be done. But if your point is just to avoid having to write code and run migrations, then well, you really want to think twice about it...

Benefits of foreign key over integerfield

I'm not sure if this is an appropriate question here. I know the answer but I don't really know why, and I need proof when I raise this to my team.
We have a number of Blog Posts on a Django Site. It's possible to "clone" one of those blog posts to copy it to another site. The way the current developer did that was to take the pk of the original post and store it as an IntegerField on the cloned post as clone_source. Therefore to get a story's clones, we do:
clones = BlogPost.all_sites.filter(clone_source=pk)
It seems to me that this would be much better structured as a foreign key relationship.
Am I right? Why or why not?
Deleted objects
If you ever decided to delete the original post, you'd need a separate query to handle whatever you expect to do with the cloned posts instead of using the on_delete kwarg of a FK.
Its an extra query
As noted in the comments, foreign keys allow you to traverse the relationships directly through the ORM relationship methods.
Data structure visualisation tools
These won't be able to traverse any further down from an integer field since it will believe it is at a leaf node.
Throughout all of this though, the elephant in the room is that a "clone" is still just duplicated data so I wonder why you don't just let a blog post be referenced more than once then you don't need to worry about how you store clones.

Django: queryset multiple conditions or gather into new object

I need to get all Comments for all Projects that includes a specific User. Meaning, all comments for all projects that a user is member of.
A user can belong to many Projects, and each Project has many Comments.
How should this be done right? So far I have solved it in my template by creating a nested for-loop, but that's not good since I need to sort the result.
I'm thinking something like:
projects = user.projects
comments = Comment
for p in projects:
for c in p.comments:
comments.append(c)
return comments
...does not seem to work.
Any clues?
I think this will do it:
query = Comment.objects.filter(project__user=person)
If the Comment model has a foreign key to project which has a foreign key to user. This will involve a SQL join statement in the database. It's better to do this on the the database because it's far more efficient. Databases are designed exactly to do this.

Custom sql for Django model

A bit of background...
I'm trying to create a custom auth backend and extend the user model. I'm using the following as a blue print:
blog post by Scott Barnham
For whatever reason, the ORM is generating invalid sql. It seems to want to do a inner join back to itself and it's failing because it can't find a field named user_ptr_id for the join.
If you do a search for this, it seems that I might not be the only one. And there is actually a reference to this in a comment on the blog post above. But, I can't seem to fix it.
It seems like I should be able to override the SQL that is getting generated. Is that correct? From what I can tell, it seem like I might do this with a custom Object manager. Correct?
However, I can't seem to find a good example of what I want to do. Everything that I see is wanting to inherit and chain them. That's not really what I want to do. I sort of just want to say something like:
hey Django! on a select, use this SQL statement. etc
Is this possible? Maybe my "googlin'" is off today, but I can't seem to find it. That leads me to believe I'm using wrong terms or something.
Please note: I'm using Django 1.3.1 with Python 2.6.5 and PostgreSQL 9.1
David,
Yes, you can override the behavior of a model by implementing an overriding Manager in the object. I found a great blog by Greg Allard on A Django Model Manager for Soft Deleting Records which runs through a soft delete, to set a field deleted to True/False and only show objects that are not deleted, or all with deleted objects.
With that in mind, I would think you could override your object's all(), or filter() methods to get what you want. As an aside, everytime I have used a pointer, "ptr" is evident in the name of the field, it is because of class inheritance. For example, class Animal():..., class Man(Animal): Man extends or is a subclass of Animal. In the database, the Man table will have an animal_ptr_id which "extends" the animal table's tuple with that id as a Man with ANIMAL fields and MAN fields JOINed.

data validation for SQLAlchemy declarative models

I'm using CherryPy, Mako templates, and SQLAlchemy in a web app. I'm coming from a Ruby on Rails background and I'm trying to set up some data validation for my models. I can't figure out the best way to ensure, say, a 'name' field has a value when some other field has a value. I tried using SAValidation but it allowed me to create new rows where a required column was blank, even when I used validates_presence_of on the column. I've been looking at WTForms but that seems to involve a lot of duplicated code--I already have my model class set up with the columns in the table, why do I need to repeat all those columns again just to say "hey this one needs a value"? I'm coming from the "skinny controller, fat model" mindset and have been looking for Rails-like methods in my model like validates_presence_of or validates_length_of. How should I go about validating the data my model receives, and ensuring Session.add/Session.merge fail when the validations fail?
Take a look at the documentation for adding validation methods. You could just add an "update" method that takes the POST dict, makes sure that required keys are present, and uses the decorated validators to set the values (raising an error if anything is awry).
I wrote SAValidation for the specific purpose of avoiding code duplication when it comes to validating model data. It works well for us, at least for our use cases.
In our tests, we have examples of the model's setup and tests to show the validation works.
API Logic Server provides business rules for SQLAlchemy models. This includes not only multi-field, multi-table validations, but multi-table validations. It's open source.
I ended up using WTForms after all.

Categories