32👍
✅
Multi-table inheritance is just OneToOneField
relation between Place and Restaurant.
place = Place.objects.get(id=1)
# Create a restaurant using existing Place
restaurant = Resturant(place_ptr=place)
restaurant.save()
13👍
place = Place.objects.get(id=1)
# Create a restaurant using existing Place
place.__class__ = Restaurant
place.save()
restaurant = place
- [Django]-Using IntellijIdea within an existing virtualenv
- [Django]-Django: Implementing a Form within a generic DetailView
- [Django]-Django-orm case-insensitive order by
9👍
While undocumented, this seems to do the trick:
restaurant(place_ptr=place).save_base(raw=True)
This solves the problem without using any hacks and is the shortest solution, also in terms of processing, using Django APIs.
While searching for this solution, I also found a slightly longer one, but using documented APIs. It is basically the same as Mariusz answer, also see this answer for more details:
from django.forms.models import model_to_dict
restaurant(place_ptr=place, **model_to_dict(place)).save()
However, this second one is more risky due to limited field set returned by the model_to_dict (see again the answer explaining the differences among various methods presented). Naturally, it also generates more DB calls because it writes to both tables.
- [Django]-ModelForm with OneToOneField in Django
- [Django]-Django: Where does "DoesNotExist" come from?
- [Django]-CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
Source:stackexchange.com