Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to filter queryset with foreign key in django

# *********** how to filter queryset with django foreign keys **********

# in models.py file
class BookedEvent(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    event = models.ForeignKey(Events, on_delete=models.CASCADE)

    
# in filters.py file
import django_filters
class BookedEventFilter(django_filters.FilterSet):
    class Meta:
        model = BookedEvent
        #use __ (double underscore) to target foreign key values
        fields = ['event__eventName', 'event__startDate','event__endDate','event__address']   

        
# in views.py file 
def booked_event_page_view(request):
   # getting queryset
    currentUser = request.user
    bookedEvents = models.BookedEvent.objects.filter(user=currentUser)
    # adding event filter
    filter = BookedEventFilter(request.GET, queryset=bookedEvents)
    bookedEvents = filter.qs
    context = {'bookedEvents': bookedEvents, 'filter':filter}
    return render(request, 'booked_events.html', context)
Comment

PREVIOUS NEXT
Code Example
Python :: python fibonacci function 
Python :: form action in django 
Python :: how to remove some characters from a string in python 
Python :: ValueError: query data dimension must match training data dimension 
Python :: how to delete previous message using discord.py 
Python :: python remove duplicates from list of dict 
Python :: Filter Pandas rows by specific string elements 
Python :: (models.W042) Auto-created primary key 
Python :: wav file to array python 
Python :: rust vs python 
Python :: python replace with something else 
Python :: how to click a div element in selenium python 
Python :: how to add captcha in django forms 
Python :: output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] IndexError: invalid index to scalar variable. 
Python :: if string in lost py 
Python :: run multiple test cases pytest 
Python :: sklearn random forest 
Python :: range of y & x in scatter 
Python :: python .findall 
Python :: Splitting strings in Python without split() 
Python :: pandas write csv 
Python :: matplotlib draw line x1, y1 
Python :: python tkinter ttk 
Python :: convert .py to exe 
Python :: len in python 
Python :: raw input python 
Python :: django sign up 
Python :: df groupby 
Python :: make tkinter text editing disabled 
Python :: pandas groupby multiple columns 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =