Skip to content

Commit

Permalink
Fix testing Rule query before saving
Browse files Browse the repository at this point in the history
When creating a new Rule and testing its query before saving it, an error like
this was happening:

  'Rule' instance needs to have a primary key value before this relationship can
  be used.

From the user's perspective, the test was not happening and the server returned
a 500 error.

When testing a new Rule that has not been saved, a temporary Rule object is
created in memory. Since that object is not saved, it does not contain a primary
key.

Due to some changes introduced in Django 4, errors are thrown if that object
without a primary key is used. To fix that issue, we manually assign a primary
key.
  • Loading branch information
vincent-olivert-riera committed May 15, 2024
1 parent fc96e6a commit 482e350
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions promgen/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -1288,6 +1288,13 @@ class RuleTest(LoginRequiredMixin, View):
def post(self, request, pk):
if pk == 0:
rule = models.Rule()
# In Django https://code.djangoproject.com/ticket/19580, some of the
# foreign key checks got stricter. We sets pk to 0 here so that it passes
# django's m2m/foreign key checks, but marks for us that it's a temporary
# rule that doesn't actually exist.
# We'll likely want to rework this assumption when we move to a different
# promql check
rule.pk = 0
rule.set_object(request.POST["content_type"], request.POST["object_id"])
else:
rule = get_object_or_404(models.Rule, id=pk)
Expand Down

0 comments on commit 482e350

Please sign in to comment.