I have a model which I would like to change the return field from a single field to a concatenated string of fields. I have done this and it works fine, the issue comes when I try and query the foreign key related to that model.
Current Code
Models.py - Items App
class Details(models.Model):
serial_number = models.CharField(max_length = 300, unique=True, null = True, blank = True)
manufacturer = models.CharField(max_length = 300, null = True, blank = True)
model_type = models.CharField(max_length = 300, null = True, blank = True)
equipment_type = models.CharField(max_length = 300, null = True, blank = True)
class Meta:
ordering = ["serial_number"]
def __unicode__(self): # Python 3: def __str__(self):
return self.serial_number
Views.py - Instruments App: Query
queryset = InstrumentAnnual.objects.get(instrument_details__serial_number = self.object.instrument_annual, current_revision = True)
NOTE: 'InstrumentAnnual' model has a foreign key to 'Details' model called 'Instrument_Details'.
New Code
Models.py - Items App
class Details(models.Model):
serial_number = models.CharField(max_length = 300, unique=True, null = True, blank = True)
manufacturer = models.CharField(max_length = 300, null = True, blank = True)
model_type = models.CharField(max_length = 300, null = True, blank = True)
equipment_type = models.CharField(max_length = 300, null = True, blank = True)
class Meta:
ordering = ["serial_number"]
def __unicode__(self): # Python 3: def __str__(self):
return u"%s %s %s" % (self.manufacturer, self.model_type, self.equipment_type)
So my issue is how do I query the above model through a foreign key as it no longer returns self.serial_number so I can't use __serial_number in the query.
My desired result is just to display manufacturer, model_type and equipment_type in the foreign key drop down instead of just a potentially meaningless serial number. If I am going about this the wrong way please let me know. Thanks in advance.
You do not have to do the queryset the way you currently do it. If you want to get the InstrumentAnnual object that belongs to a Detail object, you can simply use self.object.instrumental_annual (given that self.object is your Detail object, as it it in your example.
As to how to fix your provided query, you are currently checking for a serial number with the string representation of the InstrumentAnnual object. But that isn't your serial number anymore. Instead you would do this
queryset = InstrumentAnnual.objects.get(instrument_details__serial_number = self.object.instrument_annual.serial_number, current_revision = True)
to specify that you in fact want to check the serial number. But as already said, there is no need for this queryset, as you can easily get the InstrumentAnnual object through self.object.instrumental_annual
Related
error: 'Questions' object is not iterable
models.py code:
class Questions(models.Model):
title = models.CharField(max_length = 150)
slug = models.SlugField(max_length = 10, unique = True)
body = models.TextField()
category = models.ManyToManyField(Category, related_name = "questions")
author = models.ForeignKey(User, on_delete = models.CASCADE)
created = models.DateTimeField(auto_now_add = True)
picture = models.ImageField(upload_to = "questions/%Y/%m/%d", null = True, blank = True)
status = models.BooleanField(default = True)
def get_absolute_url(self):
return reverse("questions:ques_detail", args = [self.slug, self.id])
views.py code:
def QuestionDetail(request, question, pk):
question = get_object_or_404(Questions, slug = question, id = pk)
return render(request, "questions/ques_detail.html", {"questions": question})
urls.py code:
urlpatterns = [
path('<slug:question>/<int:pk>', QuestionDetail, name = "questiondetail")
I guess there is a misunderstanding somewhere.
Indeed what do you want to achieve ?
If you want to retrieve a single instance your code looks good but it does not make any sense to iterate on an instance.
If you want to retrieve a QuerySet, then you would have to create another view. For exemple :
def questions(request):
questions = get_list_or_404(Questions)
return render(request, "questions/ques_detail.html", {"questions": questions})
Also you should take care of naming your function and variable in a pythonic way.
Some docs might be found here
I have the following codes:
models.py
class Job(models.Model):
jobname = models.CharField(max_length = 1000)
owner = models.CharField(max_length = 150)
enabled = models.BooleanField()
freq_type = models.IntegerField(default = 1)
freq_interval = models.IntegerField(default = 0)
freq_recurrence = models.IntegerField(default = 0)
start_date=models.CharField(max_length=10)
end_date=models.CharField(max_length=10, blank = True)
start_time=models.CharField(max_length=6)
end_time=models.CharField(max_length=6, blank = True)
date_added = models.DateTimeField(auto_now_add = True, null = True)
date_modified=models.DateTimeField(auto_now = True, null = True)
version=models.IntegerField(default = 1)
class Job_removed(models.Model):
jobname = models.CharField(max_length = 1000)
owner = models.CharField(max_length = 150)
enabled = models.BooleanField(null = True)
freq_type = models.IntegerField(default = 1)
freq_interval = models.IntegerField(default = 0)
freq_recurrence = models.IntegerField(default = 0)
start_date=models.CharField(max_length=10)
end_date=models.CharField(max_length=10, blank = True)
start_time=models.CharField(max_length=6)
end_time=models.CharField(max_length=6, blank = True)
date_added = models.DateTimeField(null = True)
date_modified=models.DateTimeField(default=timezone.now)
version=models.IntegerField(null=True)
views.py
def job_delete(request,pk):
job=Job.objects.get(pk=pk)
jobdetail = Job_detail.objects.get(job=pk)
if request.method == "POST":
jobr = JobRemovedForm(request.POST)
if jobr.is_valid():
jobr.jobname = job.jobname
print(jobr.jobname)
jobr.owner = job.owner
print(jobr.owner)
jobr.enabled = job.enabled
print(jobr.enabled)
jobr.start_date = job.start_date
print(jobr.start_date)
jobr.start_time = job.start_time
print(jobr.start_time)
jobr.date_added = job.date_added
print(jobr.date_added)
jobr.version = job.version
print(jobr.version)
jobr.save()
return redirect('/job/', {'job':Job.objects.all})
else:
jobr = JobRemovedForm()
return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail, 'jobr':jobr})
return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail})
Output of my powershell for those print commands:
In the database (SQLite):
What I am trying to do is to copy from the entry from Job Table to Job_removed Table. I assign the new entry in Job_removed with the values in Job Table. It is printing correctly in my powershell but when I check my database, none of the value are entering. Why is this happening though? Can anyone explain to me and point me to the right direction to correct this? I know there are post about how to clone data to another table but it does not fit the task that I am required to do so I am not using those answers.
Update: model for Job_detail and form for JobRemovedForm
models.py
class Job_detail(models.Model):
job_type=models.IntegerField(default=1)
json = models.CharField(max_length = 1000)
job = models.ForeignKey(Job, on_delete=models.CASCADE)
forms.py
class JobRemovedForm(ModelForm):
class Meta:
model = Job_removed
fields = []
Update 2: views (I realize i didnt do commit=False) and form fields updated
views.py
def job_delete(request,pk):
job=Job.objects.get(pk=pk)
jobdetail = Job_detail.objects.get(job=pk)
if request.method == "POST":
jobr = JobRemovedForm(request.POST)
if jobr.is_valid():
jr = jobr.save(commit=False)
jr.jobname = job.jobname
print(jr.jobname)
jr.owner = job.owner
print(jr.owner)
jr.enabled = job.enabled
print(jr.enabled)
jr.start_date = job.start_date
print(jr.start_date)
jr.start_time = job.start_time
print(jr.start_time)
jr.date_added = job.date_added
print(jr.date_added)
jr.version = job.version
print(jr.version)
jr.save()
return redirect('/job/', {'job':Job.objects.all})
else:
print(jobr.errors)
jobr = JobRemovedForm()
return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail, 'jobr':jobr})
return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail})
forms.py
class JobRemovedForm(ModelForm):
class Meta:
model = Job_removed
fields = ['jobname', 'owner', 'enabled', 'start_date', 'start_time', 'date_added', 'version']
And now my powershell is showing jobr.errors of the following:
jobnameThis field is required.ownerThis field is required.start_dateThis field is required.start_timeThis field is required.date_addedThis field is required.versionThis field is required.
Actually you do not need Job_removed model because it is unuseful and not better design for a such case in general.so first remove that model and add a field called is_deleted to your job model which value should be True for deleted jobs and False for non deleted jobs.by default i make is_deleted is False so when you deleted it you can mark it as True
class Job(models.Model):
jobname = models.CharField(max_length = 1000)
owner = models.CharField(max_length = 150)
enabled = models.BooleanField()
freq_type = models.IntegerField(default = 1)
freq_interval = models.IntegerField(default = 0)
freq_recurrence = models.IntegerField(default = 0)
start_date=models.CharField(max_length=10)
end_date=models.CharField(max_length=10, blank = True)
start_time=models.CharField(max_length=6)
end_time=models.CharField(max_length=6, blank = True)
date_added = models.DateTimeField(auto_now_add = True, null = True)
date_modified=models.DateTimeField(auto_now = True, null = True)
version=models.IntegerField(default = 1)
is_delete = models.BooleanField(default=False) # new field
Delete your model remove Job_removed
2)run python manage.py makemigrations
3)run python manage.py migrate
now let us work on your views for deleting jobs.
from django.shortcuts import render,get_object_or_404,redirect
def job_delete(request,pk):
job= get_object_or_404(Job,pk=pk,is_deleted=False)
job.is_deleted = True # delete the job if it is not deleted
job.save()
return redirect('/job/')
Note:I use get_object_or_404 to raise page not found if there is no job related to the pk and i check that the job is not deleted.
now i do not know how is your other views but you should now make a little bit of change in querying jobs.if you want to query all jobs you should query jobs that is not deleted.by doing this
Job.objects.filter(is_deleted = False)
instead of
Job.objects.all()
and better approach should be to use post method for deleting jobs not get.but for now you can keep as it is.sorry for my english if you do not understand please ask me in the comments.
Update but if you want to do is it as you did.
then you do not need a form you can just copy the data from Job to Job_removed.and if you need a form you can make these fields read only.
let us do it without form
from django.shortcuts import render,get_object_or_404,redirect
def job_delete(request,pk):
job= get_object_or_404(Job,pk=pk)
jr = Job_removed()
jr.jobname = job.jobname
print(jr.jobname)
jr.owner = job.owner
print(jr.owner)
jr.enabled = job.enabled
print(jr.enabled)
jr.start_date = job.start_date
print(jr.start_date)
jr.start_time = job.start_time
print(jr.start_time)
jr.date_added = job.date_added
print(jr.date_added)
jr.version = job.version
print(jr.version)
jr.save()
job.delete() # then delete the job
return redirect('/job/')
Form is not required in this situation.
Soft delete is the best option. Have a look in to this tutorial
In a Django Modelform (Product_definition), i want to have a dropdown(Merchant name) which will show users only if the their designation in User form is "Merchant".
is it possible that I could get the list of users for the dropdown based on this condition .Please note that i don't require it to be a foreign key as connecting the models is not required.
This is the form which contains the Designation :
from django.contrib.auth.models import User
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete = models.CASCADE)
#extra UserAttribute
MERCHANT = 'MR'
FABRIC = 'FR'
WASHING = 'WS'
PRINT = 'PR'
PLANNER = 'PL'
DESIGNATION_CHOICES =(
(PLANNER,'Planner'),
(MERCHANT,'Merchant'),
(FABRIC,'Fabric'),
(WASHING,'Washing'),
(PRINT,'Printing'),
)
Designation =models.CharField(
max_length = 20,
choices = DESIGNATION_CHOICES,
default= 'PLANNER'
)
def __str__(self):
return self.user.username
and this is the form with Merchant Name where I want the names of all merchants to appear.
class Product_definition(models.Model):
Order_number = models.CharField(max_length=25,unique = True, blank = True, null = True)
style_name = models.CharField(max_length=15, blank = True, null = True)
color = models.CharField(max_length=15, blank = True, null = True)
Order_qty = models.PositiveIntegerField()
SMV = models.FloatField()
MERCHANT = models.ForeignKey(UserProfileInfo,on_delete= models.CASCADE,default='Select')
def __str__(self):
return self.Order_number
I have created a foreign key for now but I don't require it and it doesn't list the names of only the merchant in the drop down.
I think you can do it like this using ModelChoiceField:
class ProductForm(forms.ModelForm): # please use CamelCase when defining Class Names
MERCHANT = forms.ModelChoiceField(queryset=UserProfileInfo.objects.filter(Designation=UserProfileInfo.MARCHENT)) # Please use sname_case when naming attributes
class Meta:
model = Product_definition # Please use CamelCase when defining model class name
fields = '__all__'
I have a MySQL database object that stores concerts that a User plans to attend on a certain date. Since each concert entry needs to be associated with a User, I added a foreign key field for User as an attribute of the Concert model. Here is the complete model:
class Concert(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE)
concert_name = models.CharField(max_length = 120, blank = True, null = True)
venue = models.CharField(max_length = 120, blank = True, null = True)
city = models.CharField(max_length = 120, blank = True, null = True)
state = models.CharField(max_length = 120, blank = True, null = True)
country = models.CharField(max_length = 120, blank = True, null = True)
timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
updated = models.DateTimeField(auto_now_add = False, auto_now = True)
When I try to make migrations to the DB, I get a message saying: You are trying to add a non-nullable field 'user' to concert with out a default; s essentially saying that the already populated rows need to have a value. I found this SO post which seemed to be addressing a similar issue, but the default value suggested in the solution is for a charfield and I don't think that would really apply in this situation. How should I go about setting the default value of the User object?
You can use null=True:
user = models.ForeignKey(User, null=True)
Although if you look at your db actual model, you cannot see an actual Foreign Key, when you put models.ForeignKey(User) in your model you can see in your db a user_id with references, but the relation needed exists so you can make it's null=True as a default.
This is the model, in which I want to search
class itemType(models.Model):
partNumber = models.CharField(max_length = 12, null = True)
designation = models.CharField(max_length = 200, null = True)
timeCreate = models.DateTimeField() #auto update field, done in save method
timeEdit = models.DateTimeField() #auto update field, done in save method
This is the view, I want to use to prepare my results
def itemtypedetails(request, itemtype_id):
result = SearchQuerySet.models(itemType)
#how can I filter the ID??
return render_to_response('itemtypedetails.html', locals())
What I want is that my results are based on the model (itemType) and the ID of an itemType (itemtype_id).
I don't understand how to combine these two filters.
thanks for helping
Try to use .filter('your condition here')
result = SearchQuerySet.filter(ID=7).models(itemType)