Get ContentType id in Django for generic relation - django

I'm porting a project from Rails to Django with a legacy database. In Rails I had a polymorphic association that allowed me to add a footnote to any row in the database. I'm trying to implement the same thing in the Django app. I found the documentation on Generic Relations and it looks perfect. Unfortunately, I first need to create new fields in my legacy database to hold the ContentType id for the relevant models. I only used the polymorphic association with 2 tables, so all I need are those two corresponding ids from the Django app, but I can't seem to find the appropriate command for looking up a ContentType id in Django.
Any suggestions are most welcome. I tried searching through previous questions but couldn't seem to find what I am looking for. Thank you very much for you time and help.

from the docs
you can do:
>>> b = Bookmark.objects.get(url='https://www.djangoproject.com/')
>>> bookmark_type = ContentType.objects.get_for_model(b)
>>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id,
... object_id=b.id)
so just instantiate an instance of your model and then do ContentType.objects.get_for_model(<instance>).id
I think there's a way to pass just the model name, too... let me know if that would work better and I'll try to find it; I've used it in the past.

You can also get ContentType ID without creating an instance, which is more efficient if you don't have and don't need an instance but just want to get ContentType ID by model name.
ContentType.objects.get(model='bookmark').id
Notes : if the name of your model is upper case, please use lower case to search. For example: model = 'bookmark' rather than 'Bookmark'

Related

Django Many to Many - polymorphic

In a Django application, I have three models:
Service
Product
AppliedTax
I want to create a many-to-many relationship between Service and AppliedTax and between Product and AppliedTax. Normally I would have an intermediate model (i.e. AppliedTaxTaxable) with three fields (applied_tax_id, taxable_type and taxable_id) and taxable_type + taxable_id would be a composite foreign key for each related model with taxable_type having as value the name of the related model (Service or Product in my case) and the taxable_id field the id of the related record of the respective model.
I understand how to make it work with raw queries, but Is there a "Django" way to do that with a ManyToMany relationship? So far I had no luck with that. I don't have much experience with Django, but I hope there is a way to do that without using raw queries.
Help :)
Well, after some thought, I did a better search and stumbled upon django-polymorphic. Here is a pretty straightforward explanation on how it works, for a basic set up and it does what I am describing in my question. The implemented schema differs a bit from what my description, but in the end we will home one intermediate table for all associated models.

Camelcase class names for models

Is it possible to have a model whose name consists of more than one word e.g. UserProfile and use it in OneToMany relationships with User, for instance, User.hasMany(UserProfile).
Currently, i suspect that either i have not set up correctly something in models or it just is not working like that # this moment. Here is fiddle http://jsfiddle.net/kristaps_petersons/y75eQ/17/.
Help is much appreciated :)
You simply have to snake case the relationShip ids in your fixtures, and I think this will work.
The second thing is to define an id for the users.
In fact, the structures defined in the fixtures must be like the JSON you will receive from the server.
I've updated the fiddle: http://jsfiddle.net/Sly7/y75eQ/19/

Third-party-app for merging Django user objects?

I need to merge two users in a Django database.
So I wonder if there is any simple way (maybe a dedicated app) to do that?
For example:
We have user_a and user_b and some models that have foreign keys to the User model (Books, Interests, Teams and so on…).
By merging users, I want to delete the object user_b and to set all foreign keys pointing to this object to point to user_a. And – this is my main concern – I want the objects that need to be changed because they reference the to-be-deleted object to be determined automatically without having to specify a list of those Models and foreign key fields in them manually.
Is this already implemented and I'm reinventing the wheel?
Is this possible?
If not, please show me the way to do it: how can I build a list of Django models that have a foreign key to a specific model (User in my case) in runtime?
Thank you for your time.
I found this snippet http://djangosnippets.org/snippets/2283/ . I'm going to have to modify it though, to make it recursive. I will share my code once I'm done.
With Django 1.8 and beyond, you could achieve this robustly using the Model _meta API.
Specifically, you could use Options.get_fields. This will even let you handle generic relations.
You'll need to consider for each related field whether you want to add or replace on merge. This decision depends on your application logic and corresponding schema choices.
u = User.objects.get(pk=123)
related_fields = [
f for f in u._meta.get_fields()
if (f.one_to_many or f.one_to_one)
and not f.concrete
]
for f in related_fields:
# use field's attributes to perform an update

What do I use instead of ForiegnKey relationship for multi-db relation

I need to provide my users a list of choices from a model which is stored in a separate legacy database. Foreign keys aren't supported in django multi-db setups. The ideal choice would be to use a foreign key, but since thats not possible I need to some up with something else.
So instead I created an IntegerField on the other database and tried using choices to get a list of available options.
class OtherDBTable(models.Model):
client = models.IntegerField(max_length=20, choices=Client.objects.values_list('id','name'))
the problem I'm having is that the choices seem to get populated once but never refreshed. How do I ensure that whenever the client list changes that those newest options area available to pick.
What I was really looking for was a way that I could simulate the behavior of a Foreign key field, at least as far as matching up ID's go.
There wasn't a clear way to do this, since it doesn't seem like you can actually specify an additional field when you instantiate a model (you can with forms, easily)
In any case to deal with the problem, since the database is MySQL based, I ended up creating views from the tables I needed in the other database.
To build on #Yuji's answer - if you do self.fields['field'].choices = whatever in the model's __init__, whatever can be any iterable.
This means you can inherit from iterable, and have that object interface to your legacy database, or you can use a generator function (in case you are unfamiliar, look up the yield keyword).
Citing a Django's manual:
Finally, note that choices can be any iterable object -- not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever.
Why dont you want just export data from the legacy database and to import it into the new one? This could be done periodically, if the legacy database still in use.

Django auth.User

I'm developing web page with many type of users, each with different profiles properties. I would like to use built in auth system but:
a) I want to use django-registration.
b) I can point User.get_profile to only one profile model.
How to accomplish that in nice fashion?
I haven't used django-registration so I don't know what it entails. For the second part of your question one way would be to
Associate an UserProfile with every User
Add different kinds of ProfileProperty classes and link to them from UseProfile using a generic relationship.
I know, it is a bit of a stretch.
I'm not an expert nor in python, django or database but I encountered a somewhat similar issue few weeks ago and on #django someone advised me to use Generic relation to achieve that.
I created a UserProfile model that is liked (through a OneToOnefield) to the "true" profile, and using contrib.content-type and generic relation I'm able to use several distinct porfile types.
Note that should work for you if you don't fear to hit you database one more time on each get_profile().
An alternative would be to create a big table that contain all the field for all the profile type and using some kind of hook (or reimplementing a custom save()) to check the retired fields according the profile type. But it look complicated to me, especially if you want to have a lot of different profile type.
Another alternative could be to create a TextField derivated custom field and use it as a storage for a dictionary that you pickle to it on save and unpickle from it on load. With some hacking you could certainly map some of the model attribute to the dictionary key. That would allow a lot of flexibility.
Free hint for ya : I also use fixtures to test my application and forgot to check if the raw parameter of the post_save signal was True to prevent executing the UserProfile creation when using manage.py loaddata. As I had coded the creation of the "true" profile in my post_save callback the exception what kind of weird until I find out what was happening.
Usefull ressource :
defining a profile
generic relation