Whether I can set field's comment in the Model? - django

You see the MySQL tables in the Sequel Pro, every field has a Comment:
Whether I can set the field comment in the Model?
class Account(models.Model):
balance = models.CharField(max_length=16)
grade = models.CharField(max_length=1, default=1) # whether there is a property for us to set field comment?

You can't set comment on a field in django (please check this issue)
I understand the idea, but I'm afraid it doesn't have a good
usefulness/noise ratio.
The ORM doesn't aim at providing a Python interface for every feature
of the supported database engines. Its goal is "just" to provide an OO
API.
Since there's neither a clean API proposal, nor a patch, nor a
convincing explanation of the value added by this feature, I'm going
to close this ticket.
PS: you can use django raw sql queries and manually set the comment.

As I've answered in a similar question:
Ticket #13867 is now "superseded" by #18468, which was reopened and is now accepted and waiting for patches. The original rejection, after discussion on the mailing list, changed to
I think we could implement that feature. (Yes I changed my mind from six years ago when I wontfix'd the ticket.)
A partial solution, for PostgreSQL databases, is published at https://github.com/vanadium23/django-db-comments, as a post-migration hook Django app. Should not be hard to adjust it for MySQL databases.

Related

How to add fields to third party app model?

I'm working on a web page which uses Django-quiz app. When you install the django-quiz, you can create quizes, questions etc. in Admin.
Unfortunately, there is no way, how to assign Quiz to my model Language so I'm looking for a way, how to add field Language into the model Quiz.
I've tried this but it does not work. I've tried already to create a proxy model with additional field but I realised that it is not possible in proxy models.
from quiz.models import Sitting,Quiz
class QuizAddLanguage(models.Model):
quiz = models.OneToOneField(Quiz)
language = models.ForeignKey(Language)
Do you know what to do to add field to third party app model?
For this time, OneToOne should be enough - for each language there will be one quiz
Since its one to one then you can just define the relationship on your own language class, django by default, will provide you the reverse lookup meaning
language_obj.quiz
quiz_obj.language
will both be valid.
Here is a relevant Django ticket, which was closed with a resolution of "wontfix" six years ago:
https://code.djangoproject.com/ticket/14969
I think this comment provides some good information:
Comments gives you the *right* way to handle this problem -- you define an interface, and make the model itself pluggable. Not all Django's contrib apps follow this approach, but that doesn't mean we bake monkeypatching into the core -- we fix the contrib apps.
django.contrib.comments is now a standalone app, but it still makes itself relatively easy to customize. Here is the relevant documentation:
https://django-contrib-comments.readthedocs.io/en/latest/custom.html
If a third party app doesn't make itself easy to customize, I would suggest asking the developer to update it and point them to the above links for examples on how to go about doing it.

Django models architecture for full-text search in PostgreSQL

I'm building a web-site for a social interaction on a particular topic, based on threads, think of gmail, only public. There will also be some static info in vocabularies, as well as blog, how-tos, knowledge base, etc. It is django+postgres.
One of the most important requirements is a full-text search over all information, regardless of the type of a model. If the exact search phrase appears in the blog, and its twisted sister in messages, than a snippet from the blog entry should appear first in the search results and be followed by a snippet from the message. So, i need a table with all the texts indexed, and the links to _any_other_table_ in the db.
My first idea is to create a separate model with "loose reference", e.g.:
class Content(models.Model):
obj_id= CharField() # An id of the object of a given model.
model= CharField(choices=("Message", "BlogEntry", "HowTo", "EntityProfile",))
content_type= CharField(choices=("subject", "body", "description", "tags",))
body= TextField()
But it feels kind of wrong... This promises an unnecessary hassle around integrity of references when creating and re-linking instances.
So, the question is - is there any elegant solution that django would provide? What might be the most efficient architecture to solve the problem?
I am not asking for a direct answer, but rather a hint.
Thanks in advance!
I've had a lot of success working with this snippet, which uses PostgreSQL's tsearch2. I've tweaked it for various different purposes in various different ways, but basically it works very well, and is very easy to implement.
Thanks a lot for the hints!
while contenttypes is an ideal for this kind of task, it is really tempting to be DB independent
from what i've read so far, Solr is a reliable search engine, but i think, i'll go and try ElasticSearch via Haystack
thanks again!

Django end-user defined fields, how to? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Django dynamic model fields
Good Morning guys!
Scenario is the following. For some models on Django, I would like to allow the end user to define his own fields. It would be great if I could keep all Django awesome features like the ORM, so I can still do calls like field__gte to search on the model, still have field validation according to field type, etc. I've thought about two ways of doing this, and I'm more than open for new suggestions. Any feedback would be VERY appreciated.
The first approach, is the Entity-Attribute-Value ( http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model ), which django already has an app for. See http://code.google.com/p/django-custom-field/
I think this would be an OK solution, but I lose the ability to do "mymodel.objects.filter(custom_field_x=something)". Maybe there's a way to regain the ORM, any ideas? But I've heard so many bad stories about this method that I'm little scared to use it.
The second approach would be to have a database table for each of the users (probably no more than a 1000). I've read django has something in the lines of inspectdb, which actually checks which fields are there and produces the model for you. This could be useful but I think maybe I should store the fields this particular user has created and somehow dinamically tell django, hey, we also have this fields in this model. Is this possible? I know it's generally bad to have different tables for each user, but considering this scenario, how would you guys rate this method, would it be ok to have one table for each user?
The model that requires custom fields is for example Person. They might want a custom field to store address, blood type, or any other thing.
MANY THANKS in advance! Have a nice sunday!
Very similar: How to create user defined fields in Django -- but only talks about the EAV, which I would like to avoid. I'm open for new ideas!
One approach is to use a NoSQL document-based solution such as MongoDB which allows you to store objects that have a fluid structure (no such restrictions as pre-defined columns).
Pros:
No restriction on custom field types, number of types of fields, etc.
Retains ORM functionality (django-mongodb)
Other various benefits of NoSQL - which you can read about online
Avoids EAV
Cons:
Need to setup NoSQL server
Additional knowledge required on NoSQL concepts (documents vs. tables)
You may have to maintain two databases - if you decide not to migrate your entire solution to NoSQL (multi-db)
EDIT:
After reading the comments its worth pointing out that depending on which NoSQL solution you go with, you may not need reversion support. CouchDB, for example has built in support for document versioning.
what about creating another model for storing user_defined_fields?
class UserDefinedField(models.Model):
#..................
user = models.ForeignKey(User)
field_name = models.CharField(max_length=50)
field_value = models.TextField()
Then you can do UserDefinedField.objects.filter(field_name=some_name,field_value=somevalue)

django model versioning/revisions/approval - how to allow user to edit own profile but keep old online until new approved?

I am building a site where users can make changes to their publicaly displayed profile. However I need all changes to be approved by an admin before going live. Until the changes are approved their old profile will be displayed. In the admin there should be a list of profiles awaiting approval. It is preferable, but not required, to keep a history of versions.
I have looked at django-reversion, but don't think that will handle showing an old version while keeping a new one under-approval.
I'm looking for ways to achieve this with django...
Two from-the-hip ideas. How about...
Use reversion and add logic which auto-marks a profile as 'unapproved' on save() if the save is not performed by an administrator, then add a custom accessor to your code that gets the latest approved profile from the reversion archive.
Or, if reversion won't play nicely, have a 'current profile' and 'pending profile' for each user and update the FKs when the profile is approved...
This apps do exactly what you need
http://github.com/dominno/django-moderation
I've had some problems using django-moderation from dominno, which are:
Using a unique model for tracking changes in several others, with a GenericForeignKey reduces the amount of tables needed to monitor things, but it's a pain to manage. And I don't trush GenericForeignKeys for this type of task.
Deserialization of sandboxed values would invariably fail if I changed one field's name in the model. (for example, if I migrated a field change of name after monitoring it in moderation). It should at least be able to recover non bogus field values.
So I made my own app, which tackles the problems mentioned above.
It should give you what you're looking for.
https://github.com/artscoop/django-approval
It has auto approval mechanism, field selection (you can always ignore some fields, and put others to validation) and default values (for example, automatically set an object to hidden when it's created, so that it can be moderated without being visible in the first place)

How can I easily mark records as deleted in Django models instead of actually deleting them?

Instead of deleting records in my Django application, I want to just mark them as "deleted" and have them hidden from my active queries. My main reason to do this is to give the user an undelete option in case they accidentally delete a record (these records may also be needed for certain backend audit tracking.)
There are a lot of foreign key relationships, so when I mark a record as deleted I'd have to "Cascade" this delete flag to those records as well. What tools, existing projects, or methods should I use to do this?
Warning: this is an old answer and it seems that the documentation is recommending not to do that now: https://docs.djangoproject.com/en/dev/topics/db/managers/#don-t-filter-away-any-results-in-this-type-of-manager-subclass
Django offers out of the box the exact mechanism you are looking for.
You can change the manager that is used for access through related objects. If you new custom manager filters the object on a boolean field, the object flagged inactive won't show up in your requests.
See here for more details :
http://docs.djangoproject.com/en/dev/topics/db/managers/#using-managers-for-related-object-access
Nice question, I've been wondering how to efficiently do this myself.
I am not sure if this will do the trick, but django-reversion seems to do what you want, although you probably want to examine to see how it achieves this goal, as there are some inefficient ways to do it.
Another thought would be to have the dreaded boolean flag on your Models and then creating a custom manager that automatically adds the filter in, although this wouldn't work for searches across different Models. Yet another solution suggested here is to have duplicate models of everything, which seems like overkill, but may work for you. The comments there also discuss different options.
I will add that for the most part I don't consider any of these solutions worth the hassle; I usually just suck it up and filter my searches on the boolean flag. It avoids many issues that can come up if you try to get too clever. It is a pain and not very DRY, of course. A reasonable solution would be a mixture of the Custom manager while being aware of its limitations if you try searching a related model through it.
I think using a boolean 'is_active' flag is fine - you don't need to cascade the flag to related entries at the db level, you just need to keep referring to the status of the parent. This is what happens with contrib.auth's User model, remember - marking a user as not is_active doesn't prompt django to go through related models and magically try to deactivate records, rather you just keep checking the is_active attribute of the user corresponding to the related item.
For instance if each user has many bookmarks, and you don't want an inactive user's bookmarks to be visible, just ensure that bookmark.user.is_active is true. There's unlikely to be a need for an is_active flag on the bookmark itself.
Here's a quick blog tutorial from Greg Allard from a couple of years ago, but I implemented it using Django 1.3 and it was great. I added methods to my objects named soft_delete, undelete, and hard_delete, which set self.deleted=True, self.deleted=False, and returned self.delete(), respectively.
A Django Model Manager for Soft Deleting Records and How to Customize the Django Admin
There are several packages which provide this functionality: https://www.djangopackages.com/grids/g/deletion/
I'm developing one https://github.com/meteozond/django-permanent/
It replaces default Manager and QuerySet delete methods to bring in logical deletion.
It completely shadows default Django delete methods with one exception - marks models which are inherited from PermanentModel instead of deletion, even if their deletion caused by relation.