How to insert data into 1-to-1 relationship tables in django - django

i'm new to django. I use django User and 2 extended tables (profile_table, more_table), each has a one-to-one relationship with User. So under models.py, i have 2 classes (one for profile_table, the other one for more_table). When I create a new user, i'll insert basic data into auth_user table and other information into profile_talbe and more_table. How and where to build this insert method? Should i use class manager? or overrite save function? or create a class method under profile_table class?
Thanks

If you create new instance from the profile model you should write static method in the profile model class.
Example:
class Profile(models.Model):
name = models.CharField(max_length=100)
#staticmethod
def create_profile(name=name):
profile = Profile(name=name)
profile.save()
return profile

Related

Create custom page view counter in Django

I want to create my own view counter. I got inspired from django-hitcount. I read all models of this app.
In these lines:
class HitCountMixin(object):
"""
HitCountMixin provides an easy way to add a `hit_count` property to your
model that will return the related HitCount object.
"""
#property
def hit_count(self):
ctype = ContentType.objects.get_for_model(self.__class__)
hit_count, created = HitCount.objects.get_or_create(
content_type=ctype, object_pk=self.pk)
return hit_count
I couldn't understand the meaning and usage of ContentType and get_for_model(self.__class__). Can anyone help me?
Source of this mixin is here.
Since HitCountMixin can be inherited by different models in your app, HitCount model must be in some way connected to these models with a relation.
Here you can think of ContentType as a way of creating dynamic relation unlike it is with e.g. ForeignKey where you are bound to use the relation only with one model (table).
get_for_model is just Django's helper method for getting ContentType instance for given model because each model (table) would have its corresponding ContentType instance.
With example model using this mixin:
class Example(models.Model, HitCountMixin):
pass
ContentType.objects.get_for_model(self.__class__) would return ContentType instace for model Example
You can read more about ContentTypes in Django documentation

Django admin crashes when adding or editing object

I have a django model:
class Foo(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT)
def __str__(self):
return self.user.username
With the admin registered as a model admin.
When I try to either edit an existing Foo object (which I first added directly to the DB with SQL) or click 'add' to create a new Foo object, the server crashes. Does this have something to do with the fact that the User table contains about 50,000 objects, and the server is running out of memory when it tries to load the Foo admin, because it OneToOne keys out to User?
Is there a way around this?
You'll probably want to make user a raw_id_fields field, so Django won't attempt to load those 50,000 User objects.
class FooAdmin(...):
# ...
raw_id_fields = ('user',)
If you're using Django 2.0+, you can also use autocomplete_fields instead.

Create a django project from an existing database

I have a n existing MySQL database. I want to create a new django application with that database.
I read that I need to run "syncdb" each and every time when add a new model in django. That time adding a new table in database in <database_name>.<table_name> format. And fetching data from that table.
What is the correct method to fetch data from an existing database in django ?
This is my model:
from django.db import models
class Users(models.Model):
employee_id = models.CharField(max_length=30)
def __unicode__(self):
return self.employee_id
Use the Django model meta options to set db_table and db_column on your Models and Fields respectively. See these links for more info on how to use them:
https://docs.djangoproject.com/en/dev/ref/models/options/#db-table
https://docs.djangoproject.com/en/dev/ref/models/fields/#db-column

Django model manager use_for_related_fields and ModelAdmin relationships

I am having trouble getting my model manager to behave correctly when using the Admin interface. Basically, I have two models:
class Employee(models.Model):
objects = models.EmployeeManager()
username = models.CharField(max_length=45, primary_key=True)
. . .
class Eotm(models.Model): #Employee of the Month
date = models.DateField()
employee = models.ForeignKey(Employee)
. . .
And I have an EmployeeManager class that overrides the get() method, something like this:
class EmployeeManager(models.Manager):
use_for_related_fields = True
def get(self, *arguments, **keywords):
try:
return super(EmployeeManager, self).get(*arguments, **keywords)
except self.model.DoesNotExist:
#If there is no Employee matching query, try an LDAP lookup and create
#a model instance for the result, if there is one.
Basically, the idea is to have Employee objects automatically created from the information in Active Directory if they don't already exist in the database. This works well from my application code, but when I tried to create a Django admin page for the Eotm model, things weren't so nice. I replaced the default widget for ForeignKey fields with a TextInput widget so users could type a username (since username is the primary key). In theory, this should call EmployeeManager.get(username='whatever'), which would either return an Employee just like the default manager or create one and return it if one didn't already exist. The problem is, my manager is not being used.
I can't find anything in the Django documentation about using custom Manager classes and the Admin site, aside from the generic manager documentation. I did find a blog entry that talked about specifying a custom manager for ModelAdmin classes, but that doesn't really help because I don't want to change the model represented by a ModelAdmin class, but one to which it is related.
I may not be understanding what you're trying to do here, but you could use a custom Form for your Eotm model:
#admin.py
from forms import EotmAdminForm
class EotmAdmin(models.ModelAdmin):
form = EotmAdminForm
#forms.py
from django import forms
from models import Eotm, Employee
class EotmAdminForm(forms.ModelForm)
class Meta:
model = Eotm
def clean_employee(self):
username = self.cleaned_data['employee']
return Employee.get(username=username)
That, in theory, should work. I haven't tested it.

Cannot assign - must be a "UserProfile" instance

I have a class UserProfile defined which takes the default user as a foreign key.
Now another class A has a foreign key to UserProfile.
So for saving any instance in class A, how do i give it the userprofile object.
Also, does making a class UserProfile mean that class user is still used and class UserProfile is just some other table?
I need to know this as I have to take care of the user profile creation, so I should know what gets stored where?
--
Confused
So for saving any instance in class A,
how do i give it the userprofile
object.
Create a app with a model which has a models.OneToOneField(User) or a models.ForeignKey(User, unique=True).
Make your project aware of your UserProfile by pointing to it from the settings.py file AUTH_PROFILE_MODULE = 'myapp.UserProfile'.
Read the documentation.
Also, does making a class UserProfile
mean that class user is still used and
class UserProfile is just some other
table?
Yes, your database will have both a auth_user and a user_profile table. This is due to the fact that using UserProfiles doesn't mean all user have to have profiles. Only the additional fields defined in the UserProfile model will be in the user_profile table.
I need to know this as I have to take
care of the user profile creation, so
I should know what gets stored where?
James Bennett created two nice apps which with a few hours of careful reading will be of great help especially when it comes to the user registration part. Go look at django-registration and django-profiles.
I assume your UserProfile model is intended to store additional information about your users. If so, there's documentation about the best approach to do this, which in brief is:
define a model with fields for the additional information you'd like to store, or additional methods you'd like to have available, and also add a OneToOneField from your model to the User model. This will ensure only one instance of your model can be created for each User.
Set AUTH_PROFILE_MODULE to myapp.MyModel, where myapp is the app containing the model MyModel which you want to use to store extra information about your users.