I need to take a set of values, in this case the foreign key liquorID in LiquorInStore obtained with values() or values_list() and use them to filter the results by ID of it's parent db, Liquor and return those to the webpage.
This is the view, I fear I may not be using the variables correctly.
def store(request, store_id=1):
a = Store.objects.get(StoreID=store_id)
b = LiquorInStore.objects.filter(storeID__exact=a).values('liquorID')
args = {}
args['liquors'] = Liquor.objects.filter(id__exact=b)
args['a'] = a
return render(request, 'store.html', args)
Here is the models file as well in case that helps.
class LiquorInStore(models.Model):
StoreLiquorID = models.AutoField(primary_key=True)
liquorID = models.ForeignKey(Liquor)
storeID = models.ForeignKey(Store)
StorePrice = models.DecimalField('Store Price', max_digits=5, decimal_places=2)
Do it like this:
b = LiquorInStore.objects.filter(storeID__id=a.id).values_list('liquorID', flat=True)
args['liquors'] = Liquor.objects.filter(id__in=b)
Related
I have a model Field that has a OneToMany connections with TreeSensor and WeatherStation model. Im trying to pass over the queries of each treesensor/weatherstation model that match the id of each different field but get a Field 'id' expected a number but got <built-in function id>. .How do i fix that? Maybe change something on the filter ?
class Field(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, default=None)
friendly_name = models.CharField(max_length=24, blank=True)
soil_type = models.CharField(max_length=24, choices=SOIL_TYPES, blank=True)
cultivation = models.CharField(max_length=128, choices=CULTIVATIONS, blank=True)
kml = models.FileField(upload_to = user_directory_path_kml, null=True, blank=True)
class TreeSensor(models.Model):
field = models.ForeignKey(Field, on_delete=models.CASCADE)
...
class WeatherStation(models.Model):
field = models.ForeignKey(Field, on_delete=models.CASCADE)
...
view
def map(request):
field_list = models.Field.objects.filter(user = request.user)
tree_sensors = models.TreeSensor.objects.filter(field__pk = id)
weather_stations = models.WeatherStation.objects.filter(field__pk = id)
context = {
"title": "Map",
"field_list": field_list,
"tree_sensors": tree_sensors,
"weather_stations" : weather_stations,
}
template = 'agriculture/map.html'
return render(request, template, context)
On your view you are filtering some field called field by id, which is not defined nowehere....
You have a queryset of Fields, so probably you should do something like this:
def map(request):
field_list = models.Field.objects.filter(user = request.user).values_list('id', flat=True)
tree_sensors = models.TreeSensor.objects.filter(field__id__in = field_list)
weather_stations = models.WeatherStation.objects.filter(field__id__in = field_list)
#Walucas your approach was correct it was kinda different though . It works out like this :
view
def map(request):
field_list = models.Field.objects.filter(user = request.user)
tree_sensors = models.TreeSensor.objects.filter(field_id__in = field_list.values_list('id',flat=True))
weather_stations = models.WeatherStation.objects.filter(field_id__in = field_list.values_list('id',flat=True))
context = {
"title": "Map",
"field_list": field_list,
"tree_sensors": tree_sensors,
"weather_stations" : weather_stations,
}
template = 'agriculture/map.html'
return render(request, template, context)
i want to change the filtering field dynamically.
i have a model named Product and fields are title and code
class Product(models.Model):
title = models.CharField(max_length=50)
code = models.CharField(max_length=50)
my filtering field will be dynamic in views like this
def filter(request):
search_choices = {
'1': 'title__icontains',
'2': 'code__icontains',
}
col_num = request.GET.get("col_num")
value = request.GET.get("value")
search_field = search_choices.get("col_num")
qs = Product.objects.filter(search_field=value)
........
here the variable search_field is always dynamic ... so how can i achieve this
You can achieve this by passing argument as dictionary:
value = request.GET.get("value")
search_field = search_choices.get("col_num")
qs = Product.objects.filter(**{search_field: value})
I have models.py
class employees(models.Model):
emp_id=models.PositiveIntegerField()
emp_name = models.CharField(max_length = 100)
emp_lname = models.CharField(max_length = 100)
emp_loc=models.CharField(max_length=5,choices=LOCATION)
manager_id=models.ForeignKey('self',null=True,blank=True)
class leave(models.Model):
employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1')
start_date = models.DateField()
end_date = models.DateField()
status=models.CharField(max_length=1,choices=LEAVE_STATUS,default='P')
ltype=models.CharField(max_length=2,choices=LEAVE_TYPE)
message=models.CharField(max_length=500,blank=True)
class notify(models.Model):
sender_id=models.ForeignKey(leave, related_name='%(class)s_sendername')
receiver_id=models.ForeignKey(leave,related_name='%(class)s_receivername')
date_time=models.DateTimeField()
I have views.py
def accept(request):
approved_emp_id=leave.objects.filter(id=accept_id);
approving_emp_id=leave.objects.filter(employee__emp_id=request.user.username);
accept_notify=notify(sender_id=approving_emp_id, receiver_id=approved_emp_id,date_time=datetime.datetime.now(),viewed='N');
accept_notify.save()
When I want to save values to database I am getting error as ValueError: Cannot assign "<QuerySet [<leave: 121-geeta-2017-10-04-2017-10-06-C-V-2017-09-27 07:48:36.288873+00:00>]>": "notify.sender_id" must be a "leave" instance.
Where am I going wrong approving_emp_id and approved_emp_id are both leave instance only.
You are passing a QuerySet when the arguments should be an instance. A QuerySet is a list of instances. Pass only one instance. Use leave.objects.get() instead of leave.objects.filter().
objects.get() returns a single instance where objects.filter() returns a QuerySet.
def accept(request):
approved_emp_id = leave.objects.get(id = accept_id)
approving_emp_id = leave.objects.get(employee__emp_id = request.user.username)
accept_notify = notify(sender_id = approving_emp_id, receiver_id = approved_emp_id, date_time = datetime.datetime.now(), viewed = 'N')
accept_notify.save()
Another way is slicing the QuerySet.
def accept(request):
approved_emp_id = leave.objects.filter(id = accept_id)[0]
approving_emp_id = leave.objects.filter(employee__emp_id = request.user.username)[0]
accept_notify = notify(sender_id = approving_emp_id, receiver_id = approved_emp_id, date_time = datetime.datetime.now(), viewed = 'N')
accept_notify.save()
I am getting this at every attempt.
Cannot assign "u''": "Company.parent" must be a "Company" instance.
I do not know what else to do.
The view code is still half baked, sorry for that.
Am I passing wrong parameters to the form?
I have the following model:
models.py
class Company(AL_Node):
parent = models.ForeignKey('self',
related_name='children_set',
null=True,
db_index=True)
node_order_by = ['id', 'company_name']
id = models.AutoField(primary_key=True)
company_name = models.CharField(max_length=100L, db_column='company_name') # Field name made lowercase.
next_billing_date = models.DateTimeField()
last_billing_date = models.DateTimeField(null=True)
weekly = 'we'
twice_a_month = '2m'
every_two_weeks = '2w'
monthly = 'mo'
billing_period_choices = (
(weekly, 'Weekly'),
(every_two_weeks, 'Every two weeks'),
(twice_a_month, 'Every two weeks'),
(monthly, 'Monthly'),
)
billing_period = models.CharField(max_length=2,
choices=billing_period_choices,
default=weekly)
objects = CompanyManager()
The following forms.py:
class newCompany(ModelForm):
company_name = forms.CharField(label='Company Name',
widget=forms.TextInput(attrs={'class': 'oversize expand input-text'}))
billing_period = forms.ModelChoiceField
next_billing_date = forms.CharField(widget=forms.TextInput(attrs={'class': 'input-text small', 'id': 'datepicker'}))
parent = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = Company
fields = ["company_name", "parent", "billing_period", "next_billing_date"]
The following view:
def create_company(request):
userid = User.objects.get(username=request.user).id
my_company_id = CompanyUsers.objects.get(user_id=userid).company_id
my_company_name = Company.objects.get(id=my_company_id).company_name
machines = Title.objects.raw(
'select machines.id, title.name, machines.moneyin, machines.moneyout, moneyin - moneyout as profit, machines.lastmoneyinoutupdate, (select auth_user.username from auth_user where machines.operator = auth_user.id) as operator, (select auth_user.username from auth_user where machines.readers = auth_user.id) as readers from machines, title where machines.title = title.id and machines.company_id =%s',
[my_company_id])
if request.method == 'POST':
form_company = newCompany(request.POST)
if form_company.is_valid():
new_company = form_company.save(commit=False)
new_company.parent = my_company_id
if request.POST.get('select_machine'):
selected_machine = request.POST.getlist('select_machine')
percentage = request.POST.get('percentage')
if not Beneficiary.objects.check_assign_machine(my_company_id, selected_machine, percentage):
target_company_name = new_company.company_name
target_company_id = Company.objects.get(company_name=target_company_name).id
new_company.save()
Machines.objects.assign_machine(target_company_id, selected_machine)
Beneficiary.objects.create_beneficiary(percentage, target_company_name, my_company_id, selected_machine)
else:
invalid_machines = Beneficiary.objects.check_assign_machine(my_company_id, selected_machine, percentage)
return render(request, 'lhmes/createcompany.html',
{'form_company': form_company, 'machines': machines, 'my_company_name': my_company_name, 'invalid_machines' : invalid_machines})
else:
new_company.save()
else:
form_company = newCompany()
return render(request, 'lhmes/createcompany.html',
{'form_company': form_company, 'machines': machines, 'my_company_name': my_company_name})
The error message says you are trying to set a relationship with a string but Django expects the value to be an instance of the Company model. You should assign the foreign key fields with a real model instance instead of only the primary key.
I've spotted a few places in the code where you are assigning a PK:
new_company.parent = my_company_id
Where the model expects it to be an instance:
new_company.parent = Company.objects.get(id=my_company_id)
I really don't remember if this works, but you can try:
new_company.parent_id = int(my_company_id)
This would spare a trip to the database.
I have 1 question.
These are my django models.(This is just example)
class Users(models.Model):
username = models.Charfield()
class CommunityBoard(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=30)
contents = models.TextField()
I send data(nsdictionary format) to server using post
{ pk = 1 }
in views.py
def detailCommuBoard(request):
returnValues = {}
returnValues.update(csrf(request))
pk = request.POST['pk'];
detailContents = CommunityBoard.objects.filter(pk=pk)
returnValues = serializers.serialize('json', detailContents)
return HttpResponse(returnValues)
then, I got serialized data in iphone.(json format)
{
fields = {
contents = "\Uc5ed\Uc2dc \Ud30c\Uc774\Uc36c";
title = "\Ud30c\Uc774\Uc36c \Ud504\Ub85c\Uadf8\Ub798\Ubc0d";
user = 1;
};
pk = 11;
}
I want to show User model's username when make queryset, not user model's pk.
please Help me.
I think you need to change the Queryset to include that information.
detailContents = CommunityBoard.objects.filter(pk=pk).values_list('contents', 'title', 'user__username')
returnValues = serializers.serialize('json', detailContents)
You can make use of natural keys during serialization.
So you can try this:
returnValues = serializers.serialize('json', detailContents,
use_natual_keys=True)