Property from sql

Hi All.

I’m new to Django and I need some help with model fields.
I would like to create a model with a filed that value comes from a sql scalar function (DECRYPTBYPASSPHRASE in sql server), something like this:

class MyModel(models.Model):
my_col = DECRYPTBYPASSPHRASE (…)

Is it possible to achieve this without custom manager?

Many thanks for any advice.

And do what with it?

I generally suggest against adding calculated fields to the database - there are too many ways in which the calculated data can get out-of-sync with the original data. (Yes, there are exceptions to this generalization.)

So if you’re looking to calculate a value on the fly upon retrieval, that’s when you could use annotate to add the value during the query.

But beyond this, I’d need more specific details about what you’re really trying to achieve in order to provide a more detailed answer. The answer does depend as much upon need and use than just saying “I want to add a field”.

@KenWhitesell, thanks for the reply.

Sorry, I wasn’t too specific.

I have some legacy database and all my models were generated on top of that. So, I will never generate and run migrations. I just need to use these models to access the specific tables in a database, calculating some columns on the fly. In this case, I have an encrypted column and I want to decrypt it on the fly. So, the model behaves a little bit like a view (unfortunately I can’t create such db view and link it to model).

Please let me know if you need more details.

Thanks for help!

Yep, that’s where you would use annotate to dynamically add data to the result set. Also see the docs and examples at Aggregation | Django documentation | Django