I have the following models:
class Address(models.Model):
address1 = models.CharField(max_length=150, null=True)
address2 = models.CharField(max_length=150, null=True, blank=True)
city = models.CharField(max_length=50, null=True)
state_province = models.CharField(max_length=50, null=True)
zipcode = models.CharField(max_length=10, null=True)
country = models.CharField(max_length=3, default='USA', null=False)
created_at = models.DateTimeField(db_index=True, auto_now_add=True)
updated_at = models.DateTimeField(db_index=True, auto_now=True)
class Meta:
db_table = 'addresses'
and this one.....
class User(models.Model, AbstractBaseUser, PermissionsMixin):
email = models.EmailField(db_index=True, max_length=150, unique=True,
null=False)
first_name = models.CharField(max_length=45, null=False)
last_name = models.CharField(max_length=45, null=False)
mobile_phone = models.CharField(max_length=12, null=True)
profile_image = models.CharField(max_length=150, null=True)
is_staff = models.BooleanField(db_index=True, null=False, default=False)
is_active = models.BooleanField(
_('active'),
default=True,
db_index=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
addresses = models.ManyToManyField(Address),
USERNAME_FIELD = 'email'
objects = MyCustomUserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
class Meta:
db_table = 'users'
My first mystery is that by migrating the models, there is no "addresses" field in the users table, nor a pivot table in the database to keep the multiple relationships. How are ManyToMany payloads kept??
Secondly, my goal is to have multiple addresses for Users. I want Users to have multiple "Addresses" (and not each address having one User) because other models can have addresses too. I don't want the Address model to have 12 different "owner" fields with with ForeignKeys.
So. I try this:
from myApp.models import User
from myApp.models import Address
user = User(email="test#test.com", first_name="john", last_name="doe", mobile_phone="444")
# the model permits partial address fields, don't worry about that.
address = Address(city="New York", zipcode="10014")
Now I try to add the address to the user.addresses and I'm getting an error.
user.addresses.add(address)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-0337af6b1cd4> in <module>()
----> 1 user.addresses.add(address)
AttributeError: 'tuple' object has no attribute 'add'
Help?
You have a superfluous comma after the definition of the many-to-many field, which turns it into a tuple. When you've removed this, you'll find both that the migrations will create your intermediary table, and that user.addresses.add() will work.
Related
I get such an error while migrating to a database:
return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: foreign key mismatch - "user_auth_customer"
referencing "user_auth_profile"
I have checked Foreign_Keys of my models and they look good.
I have no idea why I receive that error :(
Please, help me out here.
class Customer(AbstractUser):
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = UserManager()
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
profile = models.OneToOneField("Profile", related_name="user_profile",
on_delete=models.CASCADE, null=True)
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
username = models.CharField(max_length=30, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(validators=[validators.EmailValidator()],
unique=True)
password = models.CharField(max_length=100, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
#staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False
def isExists(self):
if Customer.objects.filter(email=self.email):
return True
return False
class Meta:
verbose_name = 'Customer'
verbose_name_plural = 'Customers'
class Profile(models.Model):
first_name = models.CharField(max_length=50, null=True, blank=True)
last_name = models.CharField(max_length=50, null=True, blank=True)
phone = models.CharField(max_length=10, default='', null=True, blank=True)
email = models.EmailField(primary_key=True, unique=True, validators=[validators.EmailValidator()])
password = models.CharField(max_length=100, null=True, blank=True)
# Add a photo field
owner = models.OneToOneField(Customer, related_name='profile_owner',
on_delete=models.SET_NULL, null=True)
username = models.CharField(max_length=30, null=True, blank=True,
validators=[UnicodeUsernameValidator()])
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
if you need any else details, I can provide you with those in the comments.
You can't have both ways OneToOneField. Choose one way.
If you delete Customer's profile field, then still you will have possibility to call relation with:
customer = Customer.objects.get(id=1)
customer.profile # that will call Customer's related Profile object
Assuming, that you will change related_name='profile_owner' to simpler related_name='profile'.
Read more about OneToOneRelationships.
I used the django debug toolbar to analyse why the calls to my usermodel were so painfully slow within the django admin. There I saw that I had hundreds of duplicate calls to the content_type model:
SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id"
= 1 LIMIT 21
362 similar queries. Duplicated 4 times.
To be honest, I do not understand where these calls come from in the first place but I wanted to pre_fetch the model. However, this seems not to be possible in the normal way because there is actually no ForeignKey or any other kind of direct relationship between the models. How could I reduce those 362 content_type calls?
This is the usermodel in question:
class User(AbstractBaseUser, PermissionsMixin):
"""
Base model for the user application
"""
USERNAME_FIELD = "email"
objects = UserManager()
username_validator = None
username = None
email = models.EmailField(_("email address"), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
first_name = models.CharField(max_length=150, blank=True)
last_name = models.CharField(max_length=150, blank=True)
title_of_person = models.ForeignKey(
TitleOfPerson, on_delete=models.CASCADE, blank=True, null=True
)
is_verified = models.BooleanField(default=False)
language = models.ForeignKey(
Language, blank=True, null=True, on_delete=models.SET_NULL
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = _("User")
verbose_name_plural = _("Users")
def __str__(self) -> str:
return self.email
Thanks
class FutsalUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(
_('staff status'),
default=True,
help_text=_('Designates whether the user can log into this admin site.'),
)
objects = FutsalUserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
#property
def company_details(self):
company_data = Company.objects.filter(user= self)
if company_data :
company_data.name
return company_data
else:
return None
class Company(TimeStampedModel):
name = models.CharField(max_length=200)
hr_name = models.CharField(max_length=200)
hr_email = models.CharField(max_length=200)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, models.DO_NOTHING)
hr_verified = models.BooleanField(default=False, blank=True)
primary_phone = models.CharField(null=True, max_length=200)
followed_by = models.CharField(max_length=200,default="Not assigned")
comments = models.TextField(default="")
def __str__(self):
return self.name
1. There is no need to create a custom function in Model, to fetch other values of other table which are in relation.
[ 1 ] you should have a related_name in your company user table. like
user = models.ForeignKey(
settings.AUTH_USER_MODEL, models.DO_NOTHING, related_name='company')
# you can name company with something of your own choice.
# following will be more appropriate.
user = models.ForeignKey(
FutsalUser, models.DO_NOTHING, related_name='company')
[ 2 ] once you have a related_name, you can fetch the companies values as following.
FutsalUser.objects.all().values('email', 'is_active', 'company__name', 'company__hr_email')
2. Apart from that you can fetch the details from Company table instead.
Company.objects.all().values('name', 'user__email') # you can add more field if you want.
3
users = FatalUser.objects.all()
for user in users:
company_list = user.company_details
# this company_list will have the companies associated with user.
print(company_list)
for company in company_list:
print(company.name, company.hr_email)
Hi i am Setting the value of one field of my Django model equal to value of other field of Other model. This value should change dynamically.
This is my first model
class MainModel(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='Email Address',
max_length=255,
unique=True)
payment_online = models.ForeignKey(OnlinePayments, null=True, blank=True)
register_date = models.DateTimeField(default=datetime.now, blank=True)
purchase_date = models.CharField(max_length=32, default='')
is_csr = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
This is second model
class OnlinePayments(models.Model):
payer_email = models.CharField(max_length=255, default=None, null=True)
payer_name = models.CharField(max_length=255, default=None, null=True)
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
def __str__(self):
return self.payer_email
i want to set the value of purchase_date in MainModel equal to value of timestamp in OnlinePayments.
Any help would be appericiated
You don't actually need to maintain two fields with the same value.
I'd define a method on MainModel and get the timestamp from the related model:
class MainModel(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='Email Address',
max_length=255,
unique=True)
payment_online = models.ForeignKey(OnlinePayments, null=True, blank=True)
...
def get_purchase_date(self):
return self.payment_online.timestamp if self.payment_online else None
I think #alecxe provided a great answer.
However, if you really want to store the information in 2 places you can override the save method on the OnlinePayments model so that whenever a record is saved on that model, you can manually save the timestamp value to purchase_date in MainModel.
Add the following save method to your OnlinePayments model (filling in the purchase_date assignment under the comment)
def save(self, *args, **kwargs):
# save the value of self.timestamp into purchase_date
super(OnlinePayments, self).save(*args, **kwargs)
I'm trying to save an existing instance of a customer record. Its model has a M2M to the vehicle model (since a customer can multiple vehicles). After reading several questions/answer here, I still do not know how to solve this.
Customer model:
class Customer(models.Model):
vehicle_id = models.ManyToManyField(VehicleSale)
name = models.CharField(max_length=40, blank=True, db_index=True, null=True,
verbose_name='name')
lic = models.CharField(max_length=20, blank=True, db_index=True, null=True,
verbose_name='license')
addr = models.CharField(max_length=40, blank=True, null=True, verbose_name='address')
city = models.CharField(max_length=15, blank=True, null=True, verbose_name='city')
state = models.CharField(max_length=2, blank=True, null=True, verbose_name='state')
zip = models.CharField(max_length=10, blank=True, null=True, verbose_name='zipcode')
email = models.EmailField(blank=True, null=True, verbose_name='email')
tel1 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 1', null=True)
tel2 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 2', null=True)
ssn = models.CharField(max_length=12, blank=True, db_index=True, null=True,verbose_name='SSN')
class Meta:
db_table = 'customer'
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
self.name = self.name.upper()
self.addr = self.addr.upper()
self.city = self.city.upper()
self.state = self.state.upper()
return super(Customer, self).save(*args, **kwargs)
In the view, after defining customer as
customer = current_vehicle.customer_set.all()
I tried the following:
if 'customer' in request.POST:
if customer:
customer_form = CustomerForm(request.POST, instance=customer[0])
if customer_form.is_valid():
customer_form.save()
Also tried adding before customer_form is defined:
customer.vehicle_id = current_vehicle.id
And then this after the form:
customer_form.vehicle_id = current_vehicle.id
Form is not valid so it's not saved. Upon checking {{ form.errors}}, it always reports vehicle_id is required.
Finally, after the answer in this, I adjusted it to my scenario by adding:
obj = customer_form.save(commit=False)
and hoping to assign vehicle_id, but it fails immediately.
What am I missing?
Thanks.
1st EDIT:
The section on the view now looks as:
customer_form = CustomerForm(request.POST, instance=customer[0])
customer_form.save()
customer_form.vehicle_id.add(current_vehicle)
You are misunderstanding what a ManyToMany field is here:
customer_form.vehicle_id = current_vehicle.id
vehicle_id is defined as a ManyToMany field on your Customer model, therefore you can't just assign a single id to it. You have to add an instance of VehicleSale model, eg:
customer_form.vehicle_id.add(current_vehicle)
See docs here:
https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/
See also this answer for why you can't save until you populate the vehicle_id relation:
https://stackoverflow.com/a/2529875/202168