I Have a Django rest framework API which contained the following model:
class Points(models.Model):
mission_name = models.CharField(name='MissionName',
unique=True,
max_length=255,
blank=False,
help_text="Enter the mission's name"
)
latitude = models.FloatField(name="GDT1Latitude",
unique=False, max_length=255, blank=False,
help_text="Enter the location's Latitude, first when extracting from Google Maps.",
default=DEFAULT_VALUE)
longitude = models.FloatField(name="GDT1Longitude",
unique=False, max_length=255, blank=False,
help_text="Enter the location's Longitude, second when extracting from Google Maps.",
default=DEFAULT_VALUE)
Added User Field:
class Points(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
# rest of fields...
Iv'e added a User field, When trying to makemigrations and migrate it I get the following error:
django.db.utils.ProgrammingError: column find_second_gdt_points.user does not exist
LINE 1: SELECT "find_second_gdt_points"."id", "find_second_gdt_point...
Which I don't get, of course, this column does not exist.
This is what migartions are for, no?
Try adding default=None,
class Points(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default= None)
# rest of fields...
These errors are usually because you need to include a default null value for the new field, as well as allowing it to be nullable, it should be as simple as:
class Points(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=None)
...
The reason being, is that the migration is applied to exisiting records in your database, as well as all future records. The migration needs to know how to populate the new field (column) in the DB for existing records...
Related
i am trying to filter a data set based on a custom user model and having some difficulty with the data.
Basically, i have a registration form in which i am making user select the company they are associated with. So i have created a custom user model with a foreign key association to the company table.
Now, i am trying to query a second dataset so when user logs in, the application looks up the users company association and filters the data to only show results that are associated to the user's company choice.
any suggestion on how i can do this?
my user model is below:
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
the table that i am trying to query on has model below:
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete= models.SET_NULL, null=True)
product = models.ForeignKey(Product, on_delete= models.SET_NULL, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
requestorname = models.CharField(max_length=100, null=True)
requestorage = models.CharField(max_length=2,null=True, blank=True)
child_id = models.ForeignKey(ChildID, on_delete=models.SET_NULL, null=True, blank=True)
comments = models.CharField(max_length=100,null=True, blank=True)
requestdate_create = models.DateTimeField(auto_now_add=True)
note that both table has association to customer table using a foriegn key, so i want the user to only see the order associated to the company he/she belongs to.
appreciate any directions to help write the view. Thanks
So I was able to solve my own problem. I had to pass the request in as an argument. posting it here so folks with the same question can find answer. the view goes something like this.
def externalrequest(request):
args = request.user.customer_id
external = Order.objects.filter(customer=args)
context = {'external':external}
return render(request, 'accounts/external.html', context)
I have a webservice setup with Django backend and I am trying to delete entries for my Field objects. Each Field is assigned to a User and there are a number of Assessments done in the Field. The Assessments are linked to the Fields via a foreign key. Upon deletion of the Field object I want to also delete all the Assessments for that Field, but keep the User.
I played around with the on_deletion parameter and if I set it to CASCADE the Django admin page shows me all the associated Assessment objects if I try to delete the Field object. However, I am still getting the following error:
IntegrityError at /admin/dfto/field/ update or delete on table "field"
violates foreign key constraint "assessment_field_uuid_fkey" on table
"assessment" DETAIL: Key
(uuid)=(f3a52c10-33be-42f9-995d-482025cea17b) is still referenced from
table "assessment".
These are my models for Reference:
class Assessment(models.Model):
uuid = models.TextField(primary_key=True)
longitude = models.FloatField(blank=True, null=True)
latitude = models.FloatField(blank=True, null=True)
field_uuid = models.ForeignKey('Field', models.CASCADE, db_column='field_uuid',blank=True, null=True, related_name='assessments')
class Meta:
db_table = 'assessment'
class Field(models.Model):
uuid = models.TextField(primary_key=True)
name = models.CharField(max_length=50, blank=True, null=True)
country = models.CharField(max_length=50, blank=True, null=True)
user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email')
crop_uuid = models.ForeignKey(Crop, models.CASCADE, db_column='crop_uuid')
class Meta:
db_table = 'field'
Can someone explain to me why I am getting this error and/or provide a fix for me?
I think it's because field_uuid have argument 'models.CASCADE' so when you are deleting it, django also tries to delete any refences to this particular key, don't know how to fix it tho.
I am creating an application manages an interview process. In one interview, a candidate can be interviewed by one or more interviewer and an interviewer can interview one or more candidates. This is similar to a "round table" interview. The simplified version of the models are:
class Interviewer(models.Model):
interviewer_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=200, blank=False, null=False)
last_name = models.CharField(max_length=200, blank=False, null=False)
candidates = models.ManyToManyField('Candidate', through='Interview')
class Candidate(models.Model):
candidate_id = models.PositiveIntegerField(
primary_key=True, blank=False, null=False)
first_name = models.CharField(max_length=200, blank=False, null=False)
last_name = models.CharField(max_length=200, blank=False, null=False
class Interview(models.Model):
interview_name = models.CharField(max_length=200, blank=True, null=True)
candidates = models.ForeignKey(
Candidate, on_delete=models.CASCADE, blank=True, null=True, related_name='candidates')
interviewers = models.ForeignKey(
Interviewer, on_delete=models.CASCADE, blank=True, null=True, related_name='interviewers')
In Django admin, for the Interview model, adding an entry for an interview would mean that I would have to create the entry for each candidate and interviewer. This process is cumbersome if there are a lot of candidates and/or interviewers. What I would like to do is to add all candidates and the interviewers for a particular interview.
I changed my model to use ModelMultipleChoiceField form instead of the default SelectField for Django uses for Foreign Keys.
class InterviewAdminForm(forms.ModelForm):
interviewers = forms.ModelMultipleChoiceField(
queryset=Interviewer.objects.all(),
widget=FilteredSelectMultiple(
verbose_name='interviewers', is_stacked=False
)
)
candidates = forms.ModelMultipleChoiceField(
queryset=Candidate.objects.all(),
widget=FilteredSelectMultiple(
verbose_name='candidates', is_stacked=False
)
)
class Meta:
model = Interview
fields = '__all__'
#admin.register(Interview)
class InterviewAdmin(admin.ModelAdmin):
form = InterviewAdminForm
This now displays a ModelMultipleChoiceField with a FilteredSelectMultiple widget which I can use to select the candidates and interviewers for a particular interview.
The problem is when I click on save it shows the following error
Cannot assign "<QuerySet [<Candidate: 11111111(John Doe)>, <Candidate: 22222222(Mary Moe)>]>": "Interview.candidates" must be a "Candidate" instance.
I reckon that it is getting all the candidates I chose from the ModelMultipleChoiceField as a query set and trying to add it to the database.
How can I instruct Django admin to add it as 2 separate records?
Edit: To make my question clearer
I am looking for a shorthand way to auto add multiple records as per my model definition.
Also, if my model definition isn't correct for what I would like to achieve, it would be great if you could provide me with a correct model definition.
Hopefully this isn't asking two questions in one.
I'm creating a population script, from an MysqlDatabase to Django Models.
Im looping through my receiving data from the Mysql and thats going good.
Now I have to write it to the Django Database...
mdl, succeeded = models.User.objects.get_or_create(
name=name,
password=password,
email=email
)
I'm printing succeeded so I can see what the feedback is, but all it gives me is False
My Django Model User is edited so all fields can be blank and allows NULL or have a default
My Model User:
username = models.CharField(max_length=20, blank=True, null=True)
slug = models.SlugField(null=True, blank=True)
email = models.EmailField(unique=True, null=True)
name = models.CharField("First and last name", max_length=100)
uses_metric = models.BooleanField(default=True)
position = models.CharField("Position", max_length=70, blank=True, null=True,)
utility = models.ForeignKey(Utility, default=1, blank=True, null=True)
supplier = models.ForeignKey(Supplier, default=1, blank=True, null=True)
currency = models.ForeignKey(Currency, default=1)
phone = models.CharField("Direct phone number", max_length=40, blank=True, default='+')
gets_notifications_on_reply = models.BooleanField("Receive notifications", default=False)
memberlist = models.BooleanField("Show member in memberslist", default=True)
registration_date = models.IntegerField(default=floor(time.time()), blank=True, null=True)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Deselect this instead of deleting accounts.'
),
)
USERNAME_FIELD = 'email'
Please check your database. This means that the User objects you are querying from there already exists. This might be due to the object already existing or alternatively your code not using the correct database. Since migrations, often use multiple databases this might be a problem as well.
According to the Django documentation, get_or_create() does not return an object and a status succeeded but instead a flag created, which indicates if this object has been newly created or already existed in the database. If it already existed, the created flag (succeeded in your code) is False.
If you want to make sure that the error is not due to objects already existing, take one data pair for which created is false and try to retrieve it using the model's get() method. If this throws a DoesNotExist error then something else is the problem. If it returns an object then that object already existed.
I have the following model
#python_2_unicode_compatible
class Booking(models.Model):
session = models.ForeignKey(verbose_name=_('Session'), to=Session, default=None, null=False, blank=False)
quantity = models.PositiveIntegerField(verbose_name=_('Quantity'), default=1, null=False, blank=False)
price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2,
default=None, null=False, blank=False)
name = models.CharField(verbose_name=_('Name'), max_length=100, default=None, null=False, blank=False)
email = models.EmailField(verbose_name=_('Email'), default=None, null=True, blank=True)
phone_number = models.CharField(verbose_name=_('Phone Number'), max_length=30, default=None, null=True, blank=True)
Say I need to change my email and phone_number fields. I want them to have null=False and blank=False. Do these alterations require a new migration?
Yes they do. null=False requires a change to the database schema itself; blank=False does not, but Django needs a migration anyway so that the migration runner's internal graph of the model state is up to date.
Sure. To check it you can run python manage.py makemigrations --dry-run (the --dry-run doesn't save a new migration file, but shows if it's necessary)
https://docs.djangoproject.com/en/1.11/topics/db/models/#field-options
Django document says:
null
If True, Django will store empty values as NULL in the database. Default >is False.
blank
If True, the field is allowed to be blank. Default is False.
Note that this is different than null. null is purely database-related,
whereas blank is validation-related. If a field has blank=True, form
validation will allow entry of an empty value. If a field has blank=False,
the field will be required.
For change in null you need to migrate
For change in blank you need not to migrate, because its admin form related
Sure they do. Every change you made to your model fields (from simply altering the help_text to completely rename a model field) requires to makemigrations and migrate in order to reconstruct your model in the future.