Home > OS >  Check if foreignKey exists
Check if foreignKey exists

Time:11-29

I need a way to check if the record linked to the foreignKey has already been created.

I have 2 models, project and fundamentals. Fundamentals has a ForeignKey to the project so that and fundamentals being added are linked to that project.

class Project(models.Model):

    project_name = models.CharField(max_length=50, blank=False, unique=True)
    project_website = models.URLField(max_length=50, blank=True)
    project_description = models.TextField(blank=True)
    ckeditor_classic = models.TextField(blank=True)
    project_category = models.CharField(max_length=15, blank=True)
   
    def __str__(self):
        return str(self.project_name)

class Fundamentals(models.Model):

    project_name = models.ForeignKey(Project, to_field='project_name', on_delete=models.CASCADE)
    project_roadmap = models.CharField(max_length=25, blank=True)
    project_tier_entry_level = models.CharField(max_length=25, blank=True)
    project_tier_entry_level_notes = models.CharField(max_length=25, blank=True)
    project_rebranded = models.CharField(max_length=25, blank=True)
    
    def __str__(self):
        return str(self.project_name)

So in my view I'm trying to render a page based upon If the PK already exists in the fundamentals model.

pk = Fundamentals.objects.filter(pk=project_id)
if pk:
    return MyPage

else: 
    return MyPage

Update:

@login_required
def Add_or_updateFundamentals(request,project_id):
    project = Project.objects.filter(pk=project_id)
    check_exist = Fundamentals.objects.filter(project_name_id=project_id)
    if request.method == 'POST':
        if check_exist:
            form = AddFundamentalsForm(request.POST,instance=project[0])
        else:
            form = AddFundamentalsForm(request.POST)
        if form.is_valid():
            if not check_exist:
                 form.instance.project = project
            form.save()
            return redirect('dashboard.html')
    else:
        if check_exist:
            form = AddFundamentalsForm(instance=project[0])
            return render(request, 'pages/update_fundamentals.html', {'project': project, "form": form})
        else:
            form = AddFundamentalsForm()
            return render(request, 'pages/add_fundamentals.html', {'project': project, "form": form})

CodePudding user response:

You can check if there is at least one Fundamentals object that exists for the given project_id with:

fundamentals = Fundamentals.objects.filter(project_name_id=project_id)
if fundamentals:
    return MyPage
else: 
    return MyPage

By checking if fundamentals we make a query to retrieve all related Fundamentals. You can thus use Fundamentals after the if clause and it will not make a new SQL query if you enumerate for example over fundamentals.

CodePudding user response:

Chack this....

view.py

def Funcation_name(request, pk):
    project= get_object_or_404(project, pk=pk)
    if fundamentals.exists():
        messages.error(request, "Sorry can't be deleted.")
        return redirect('project:view_project')
# also tried
# if project in get_user_model().objects.filter(fundamentals__project=project).exists():
    elif request.method == 'POST' and 'delete_single' in request.POST:
        project.delete()
        messages.success(request, '{} deleted.'.format(project.name))
        return redirect('project:view_project')

model.py

class Fundamentals(models.Model):
    project_name = models.ForeignKey(Project, to_field='project_name', on_delete=models.CASCADE,blank=True, related_name='project')
    #.....
  • Related