Django: How to implement system flags - django

I am developing an application in Django and I am curious on how I can go about adding a model such that only 1 row is only ever present (i.e. Singleton).
As an example, I'd like to maintain a set of boolean flags of the application i'm running as to whether: it's on or off (so I can manually turn it on or off, perhaps even per module).
I can't see any part of the docs explaining a good way to go about setting this up.
Any suggestions?

Not sure from you explanation in what context you require this but I have a model which holds a number of key/value pairs used in validator checks and other things. The keys are all needed by each implementation of the project but the values will differ between projects. The values should be maintainable by an admin user. The values usually do not need to change very much once set. Given that, I decided to put them in a model. It is a bit weird but simple enough.
You should be able to limit write access to the model to the one row for either your app or your users through your code.
only ever reference the first row in the QuerySet
row = MyVariables.objects.all()[0]
Test if there are rows first. if you think there might accidentally be more than one record then make sure it is ordered (but that should never happen if you did (1) correctly.

There are a couple of apps already dealing with this, check out http://djangopackages.com/grids/g/live-setting/

I'm also a bit confused on your goal, but I'd recommend looking at the Model Instance section of the docs. You should probably look at customizing the validation or cleaning of the model.
If your goal is to only have 1 row flagged in the table for your model: during the validation you can run a query to see if any other row is flagged, and update them to be not flagged. (or delete them).
This question Unique BooleanField value in Django may be helpful.

Related

Declarative mechanism for Django model rows

With some frequency, I end up with models who contents are approximately constant. For example, I might have a set of plans that users can sign up for, with various attributes -- ID, name, order in the list of plans, cost, whether the purchaser needs to be a student/FOSS project/etc.. I'm going to rarely add/remove/change rows, and when I do there's likely going to be code changes too (eg, to change landing pages), so I'd like the contents of the model (not just the schema) to be managed in the code rather than through the Django admin (and consequently use pull requests to manage them, make sure test deploys are in sync, etc.). I'd also like it to be in the database, though, so I can select them using any column of the model, filter for things like "show me any project owned by a paid account", etc..
What are good ways of handling this?
I think my ideal would be something like "have a list of model instances in my code, and either Django's ORM magically pretends they're actually in the database, or makemigrations makes data migrations for me", but I don't think that exists?
The two workable approaches that come to mind are to either write data migrations by hand or use regular classes (or dicts) and write whatever getters and filters I actually want by hand.
Data migrations give me all the Django ORM functionality I might want, but any time I change a row I need to write a migration by hand, and figuring out the actual state involves either looking in the Django admin or looking through all the data migrations to figure out their combined impact. (Oh, and if somebody accidentally deletes the objects in the database (most like on a test install...) or a migration is screwy recovering will be a mess.)
Just using non-ORM classes in the source is a clearer, more declarative approach, but I need to replacements for many things I might normally do in the ORM (.objects.get(...), __plan__is_student, .values(plan__is_student).annotate(...), etc.).
Which of these approaches is better presumably depends on how much ORM functionality I actually want and how often I expect to be changing things.
Are there other good approaches for this? Am I missing some Django feature (or add-on) that makes this easier?

If I use django, I should not care about any MySQl optimization like indexation?

If I use django, I should not care about any MySQl optimization like indexation or something? Django automatically creates everything? Explain please
Answer: you should care, but not at first (usually).
Django doesn't take care of everything for you, only the basic/initial indexes (if you use migration tool and not creating the tables manually).
The index is related to the actual data that will be stored in the table, not only the table structure, somthing that is not known by django during the tables creation. Some indexs you get for "free", by creating unique constraints etc. (assuming you use tools like south that does that for you) but not real optimizations - this you'll have to do on your own when the time comes.
Some optimizations can be done by "telling" Django which indexes should be added, but you will have to specify it yourself.
No, Django only creates indices required by the database system, for example when creating foreign keys. You will have to optimise your database yourself, more on that in the documentation.
You can tell Django that certain model fields should be used as an index:
https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.db_index
You can also index columns together:
https://docs.djangoproject.com/en/1.10/ref/models/options/#django.db.models.Options.index_together
Yes, you are right...with Django you can generate your database from your model (classes), you have to use specifics inheritance and types but it's pretty easy to handle and of course it's as optimal as could be needed.

Django example of a form that submits multiple instances into a database?

I need a django form that submits multiple separate requests, and can't find an example of how to do this without a lot of customization. I.e., suppose there is a form that is used by a car repair shop. The form will list all the possible repairs that the shop is capable of doing, and the user will select which repairs they want to have done (i.e., using checkboes.)
Each repair can be assigned to a different mechanic. Each repair can also be cancelled or declared to be done, independent of the other repairs. That seems to require that each repair become a separate instance in a database.
Additionally, each repair job can be only performed by certain mechanic. So I need the ability to associate each repair job to it's own unique list of mechanics to choose from.
Has anyone seen an example of a django form, that does something like this? Thanks.
This is what formsets (and model formsets) are for.
It's been a while since the question is asked and I had the same problem:
I solved it by instance = form.save(commit=False), then setting the different attributes, then instances.save(force_insert=True), then deleting the form.instance.id....
HOWEVER this means that all fields that are eventually overwritten in the save method stay after the frist call to save()... This bit me hard!
How did you end up doing it?

Can i build up some wiki/ google doc type editor by php???

it seems that the google doc/wiki is difficult if i code it from the zero
So, are there any kinds of api/plugin already have those code for php.
Also, how can wiki handle the parallel editing?? Say, one have update the content when the other one is updating. How can the latter one get the most updated information ????
Otherwise the updated content will be erase once the latter one submit update .
Thanks
I'm not sure about the first part of your question, but as for the parallel editing:
It seems to me that you're basically coding a CMS system. As with most CMSs (CMSii?), you're going to want every article to have two possible states: checked in or checked out. That way, you eliminate the possibility of 2 people working on the same article simultaneously.
So basically, in your database table that holds your article entries, you'd want a row called something like checked_out, which defaults to 0.
When an editor clicks to edit an article, your code first checks to make sure checked_out == 0. That way it knows you're the only one working on that particular article. Then, if it does allow you to work on the article, set checked_out to 1. When you click to save/update/whatever the article, make sure it sets checked_out back to 0.
Seems like the simplest solution to me.

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.