how to get foreign key fields using reverse lookup in python/django ajax request (json) - ajax

---models.py---
class Products(models.Model):
category = models.ForeignKey(Category)
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
class Image(models.Model):
property = models.ForeignKey(Products, related_name='images')
image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
---views.py----
if request.is_ajax():
query = Products.objects.all()
p = Paginator(query, 4)
pagedata = p.page(1)
jsondata = serializers.serialize('json', pagedata.object_list)
data = json.dumps({'id' : jsondata,})
return HttpResponse(data, content_type='application/json')
now in ajax data are in (pk, category, name, slug ,price)
but i also want foreign key field i.e 'image' using reverse lookup in ajax. i have already tried list but i want to do using reverse lookup..

You cannot use serializers.serialize and then json.dumps on your stuff. serializers.serialize is basically doing the same thing as json.dumps, to convert a python object into json string. What you need to do is manually construct a dictionary that contains all your data. You might need to loop through the Product list because there's no way to query for reverse relationships for each item in one run.

Related

Using Django/html forms can I pass multiple user inputs/values into a list to return/filter a database

I would like to filter or return certain data sets with the same "lookup_ref" but I would like to be able to look up multiple "lookup_ref" at one time.
I have searched and I can't find a way of doing this... my thoughts are:
with form checkboxes to see which data sets the user would like to return
use that input to create a list
only return data base entries which have the "lookup_ref" in that list.
have I gone down the wrong route? is there a better way of doing this?
models.pys
class qtable(models.Model):
lookup_ref_choices = (
('gen', 'gen'),
('stolen_car', 'stolen_car'),
('assault', 'assault'),
)
lookup_ref = models.CharField(choices = lookup_ref_choices, max_length=20)
quest = models.CharField(max_length = 500)
order = models.FloatField(default = None)
views.py
def get_user_input(request):
form = Input_Form
context = {'form':form}
return render(request, 'input.html',context )
forms.py
class Input_Form(forms.ModelForm):
class Meta:
model = qtable
fields = "__all__"
exclude = ['quest', 'order']
qtable = forms.ModelMultipleChoiceField(
widget = forms.CheckboxSelectMultiple,
queryset = qtable.objects.all()
)

How to use index in search API in elasticsearch-dsl(5.4.0)

I'm using elasticsearch-dsl(5.4.0) and elasticsearch(5.5.3). I defined EsTask class with an inner class named Meta class as follows in model layer file:
/task_models.py
class EsTask(DocType):
id = Keyword()
catagory_id = Integer()
name = Text(analyzer='ik_max_word', search_analyzer='ik_smart')
priority_level = Integer()
related_id = Keyword()
parent_id = Keyword()
creator_id = Keyword()
created_at = Date()
deleted_at = Date()
class Meta:
index = 'task_es'
doc_type = 'main'
I call search API in controller layer file:
/task.py
s = EsTask.search().filter('bool', must_not=elasticsearch_dsl.Q('exists', field='deleted_at'))
May I use keyword argument calling search() like search(index='task_es', doc_type='main') as expected if I want to ensure the search API use the indexes I defined in Meta Class above? Or that is necessarily and I can just leave search API without any argument?
You can leave it without any arguments as it will do it automatically.
Hope this helps!

How to concatenate an auto increment value before inserting into database in laravel

In my table I have a field that needs to be the same value as the id field which is auto increment and then the value is concatenated with certain strings.
How do I do this in store function of my controller?
I'm thinking of doing update right after insertion but I don't know how to get the inserted id, and that might be a problem if two or more users doing the same insertion into database at the same time.
Thanks
UPDATE:
in my store controller:
public function store(Request $request)
{
$kartukeluarga = new kartukeluarga();
$kartukeluarga->nomorkk = $request->input("nomorkk");
$kartukeluarga->kepalakeluarga = $request->input("kepalakeluarga");
$kartukeluarga->alamat = $request->input("alamat");
$kartukeluarga->save();
return redirect()->route('kk.index')->with('message', 'Item created successfully.');
}
the new field I want to add is 'rekamMedik' which doesn't need an input form but automatically concatenate the id and this string "kk-value of the id"
You can save details and then update that column.
If you have model Test.
$test = new Test();
$test->column_1 = "abc";
$test->column_2 = "def";
$test->column_x = ""; // Set Empty to the column where you will save id later
$test->save();
$test->column_x = "string".$test->id;
$test->save();
This might work.

Initializing a django modelform with data from url

I have two models for store and city:
class City(models.Model):
name = models.CharField()
slug = models.SlugField()
class Store(models.Model):
name = models.CharField()
slug = models.SlugField()
city = models.ForeignKey(City)
If I have my Add Store url designed as
r^'mysite.com/city/(?[-\w]+)/venue/add$'
where the represents the City.slug field can I initialize a StoreForm that automatically populates the Store.city field from the url data?
In your template, define your link as follows.
{%url somename relevant_slug_text%}
Or :
href='/mysite.com/city/{{slug_text}}/venue/add'
In your url conf, define your url like:
url(r^'mysite.com/city/(?P<slug_text>\w+)/venue/add$', 'func_name', name='somename')
So, you can pass the value of relelvant_slug_text variable to your url as slug_text, and in your function definiton:
def func_name(request, slug_text):
So , you can pass text value to your funcrtion with slug_text parameter...
EDIT:
There are tow ways...
One:
Crete your city selection form using ModelForm..., then inthe second step, use posted data to populate your form again like:
form = StoreForm(request.POST)
then you can render this form to your template...
But if it is not possible o use this, yo ucan do the following...
Since you are using ModelForm to create your forms:
class StoreForm(forms.ModelForm):
# your form field definitions are here
im your function, just override city field, but at this point, since you use modelform, your form thml will be created as
<select>
<option value="id of record">"unicode value of record"</option>
So, you have record id's as option values. And you have slug_field values to initialize your field. So you have to get related city to use it...
my_city = City.objects.get(slug=<your_slug_value>)
Now you can override the form, but you must do it before you pass your form to a variable to render to your template...
StoreForm.base_fields['city'] = forms.ModelChoiceField(queryset=City.objects.all(), initial=my_city)
form = StoreForm()

Django ModelForms: Trying to save a form using a foreign key ID

I'm trying to create a new Topic and the category id is dynamically determined in javascript on the client side. The problem i'm having is I pass the category id and I want to lookup the correct category object, but using a model form, it checks if the category is an instance of Category before I can assign it and save it.
--model.py--
class Topic(models.Model):
category = models.ForeignKey(Category)
--form.py--
class TopicForm(ModelForm):
category = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = Topic
fields = ('category')
--view.py--
form = TopicForm(request.POST)
if form.is_valid():
form.save(commit=False) # throws exception category is not a Category instance
form.category = Category.objects.get(pk=form.cleaned_data.get('category'))
form.save()
Use a ModelChoiceField instead of the IntegerField in your form. See the built-in fields reference
Following Oggy's suggestion, I changed it to a ModelChoiceField and now Django does all the magic behind the scenes.
category = forms.ModelChoiceField(Category.objects.all(), widget=forms.HiddenInput())
Now I hope the queryset doesn't get evaluated, since it's not necessary and there are 90,000 records. :)

Resources