I want to search three models using forms in Django which are related by Foreignkey. And I also want to display a list of this search result with their respective details. The idea is that, I have the following django models; Event, Ticket, and Pin. And I want to search using the Event name but I can't figure out what is really the issue with my code I am having error which says Field 'id' expected a number but got 'Birth Day' so below is what I tried,
Models:
class Event(models.Model):
event_name = models.CharField(max_length=100)
date = models.DateField(auto_now_add=False, auto_now=False, null=False)
event_venue = models.CharField(max_length=200)
event_logo = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images')
added_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.event_name}"
#Prepare the url path for the Model
def get_absolute_url(self):
return reverse("event_detail", args=[str(self.id)])
class Ticket(models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE)
price = models.PositiveIntegerField()
category = models.CharField(max_length=100, choices=PASS, default=None, blank=True, null=True)
added_date = models.DateField(auto_now_add=True)
def __str__(self):
return f"{self.event} "
#Prepare the url path for the Model
def get_absolute_url(self):
return reverse("ticket-detail", args=[str(self.id)])
def generate_pin():
return ''.join(str(randint(0, 9)) for _ in range(6))
class Pin(models.Model):
ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
value = models.CharField(max_length=6, default=generate_pin, blank=True)
added = models.DateTimeField(auto_now_add=True, blank=False)
reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
status = models.CharField(max_length=30, default='Not Activated')
#Save Reference Number
def save(self, *args, **kwargs):
self.reference == str(uuid.uuid4())
super().save(*args, **kwargs)
def __unicode__(self):
return self.ticket
class Meta:
unique_together = ["ticket", "value"]
def __str__(self):
return f"{self.ticket}"
def get_absolute_url(self):
return reverse("pin-detail", args=[str(self.id)])
My Views code
def Pin_Search_List(request):
context = {}
#Search PIN Form
searchForm = SearchEventTicketForm(request.GET or None)
if searchForm.is_valid():
#Value of search form
value = searchForm.cleaned_data['value']
#Filter PIN by Events using Q Objects
#event_filter = Q(ticket__event_icontains = value)
#Apply the Profile Object Filter
list_pins = Pin.objects.filter(ticket__event=value)
else:
list_pins = Pin.objects.all()
page_title = "Search and Print PINs"
context.update ({
'page_title':page_title,
'list_pins':list_pins,
'searchForm':searchForm,
})
return render(request, 'user/pin_list.html', context)
Please understand that the searchForm in the forms.py has not issue.
CodePudding user response:
Do
Pin.objects.filter(ticket__event__event_name__icontains=value)