so i am going straight forward in most efficient way to create pivot table and store data in pivot table.
lets say, hotel and its amenities are in many to many relationship so, in hotels model
class HotelInventory(models.Model):
other fields here ,
amenities=models.ManyToManyField(HotelAmenities) // this line will create many to many pivot table
now on migrating it will create pivot table with hotel_id and amenities_id as its field.
now store individual amenities on amenities table and then,
on creating hotel inventory:
create.html
<select class="form-control mr-sm-2 " value="" name="amenities_id" multiple>
{% for things in hotelamenities %}
<option value="{{things.id}}">{{things.name}}{{things.id}}</option>
{% endfor %}
</select>
this is for multiple selection of amenities
now, in store function , of function where you perform store:
class InventoryCreate(SuccessMessageMixin,CreateView):
template_name = 'hotelInventory/create.html'
model=HotelInventory
form_class=HotelInvForm
success_message='Information Added Successfully'
success_url=reverse_lazy('hotel:hotelinv-index')
def form_valid(self,form):
inv=form.save(commit=False)
inv.save()
amenitiy=form.data.getlist('amenities_id')
for amenity in amenitiy:
inv.amenities.add(amenity)
return redirect('hotel:hotelinv-index')
Ok, this much is enough for storing data in pivot table,
No comments:
Post a Comment