We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Cannot create new shifts: ValueError: 'Shift' instance needs to have a primary key value before this relationship can be used.
Sentry Issue: [CONCREXIT-KK](https://sentry.io/organizations/thalia/issues/3788518453/?referrer=github_integration)

```
ValueError: 'Shift' instance needs to have a primary key value before this relationship can be used.
(14 additional frame(s) were not displayed)
...
  File "django/forms/models.py", line 492, in _post_clean
    self.instance.full_clean(exclude=exclude, validate_unique=False)
  File "django/db/models/base.py", line 1452, in full_clean
    self.clean()
  File "sales/models/shift.py", line 69, in clean
    if self.orders.filter(created_at__lt=self.start):
  File "django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "django/db/models/fields/related_descriptors.py", line 687, in get_queryset
    raise ValueError(
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `website/sales/models/shift.py`
Content:
```
1 from django.core.exceptions import ValidationError
2 from django.db import models
3 from django.db.models import Count, Q, Sum
4 from django.db.models.expressions import Value
5 from django.db.models.functions import Coalesce
6 from django.utils import timezone
7 from django.utils.translation import gettext_lazy as _
8 
9 from queryable_properties.managers import QueryablePropertiesManager
10 from queryable_properties.properties import AggregateProperty, RangeCheckProperty
11 
12 from activemembers.models import MemberGroup
13 from payments.models import PaymentAmountField
14 from sales.models.product import ProductList
15 
16 
17 class Shift(models.Model):
18     class Meta:
19         permissions = [
20             ("override_manager", _("Can access all shifts as manager")),
21         ]
22 
23     objects = QueryablePropertiesManager()
24 
25     start = models.DateTimeField(
26         verbose_name=_("start"),
27         blank=False,
28         null=False,
29     )
30     end = models.DateTimeField(
31         verbose_name=_("end"),
32         blank=False,
33         null=False,
34         help_text=_(
35             "The end time is only indicative and does not prevent orders being created after the shift has ended. This only happens after locking the shift."
36         ),
37     )
38 
39     title = models.CharField(
40         verbose_name=_("title"), blank=True, null=True, max_length=100
41     )
42 
43     product_list = models.ForeignKey(
44         ProductList,
45         verbose_name=_("product list"),
46         blank=False,
47         null=False,
48         on_delete=models.PROTECT,
49     )
50 
51     managers = models.ManyToManyField(
52         MemberGroup, verbose_name=_("managers"), related_name="manager_shifts"
53     )
54 
55     locked = models.BooleanField(
56         verbose_name=_("locked"),
57         blank=False,
58         null=False,
59         default=False,
60         help_text=_(
61             "Prevent orders being changed or created for this shift. This will also clean up all unpaid orders in this shift."
62         ),
63     )
64 
65     def clean(self):
66         super().clean()
67         errors = {}
68 
69         if self.orders.filter(created_at__lt=self.start):
70             errors.update(
71                 {
72                     "start": _(
73                         "There are already orders created in this shift before this start time."
74                     )
75                 }
76             )
77 
78         if self.end and self.start and self.end <= self.start:
79             errors.update({"end": _("End cannot be before start.")})
80 
81         if errors:
82             raise ValidationError(errors)
83 
84     def save(
85         self, force_insert=False, force_update=False, using=None, update_fields=None
86     ):
87         if self.locked:
88             self.orders.filter(
89                 (Q(payment__isnull=True) & Q(total_amount__gt=0))
90                 | Q(order_items__isnull=True)
91             ).delete()
92 
93         return super().save(force_insert, force_update, using, update_fields)
94 
95     active = RangeCheckProperty("start", "end", timezone.now)
96 
97     total_revenue = AggregateProperty(
98         Sum(
99             Coalesce("orders___total_amount", Value(0.00)),
100             output_field=PaymentAmountField(allow_zero=True),
101         )
102     )
103 
104     total_revenue_paid = AggregateProperty(
105         Sum(
106             Coalesce("orders__payment__amount", Value(0.00)),
107             output_field=PaymentAmountField(allow_zero=True),
108         )
109     )
110 
111     num_orders = AggregateProperty(
112         Count(
113             "orders",
114         )
115     )
116 
117     num_orders_paid = AggregateProperty(
118         Count(
119             "orders",
120             filter=Q(orders___is_free=True)
121             | Q(
122                 orders__payment__isnull=False,  # or the order is free
123             ),
124         )
125     )
126 
127     @property
128     def product_sales(self):
129         qs = (
130             self.orders.exclude(order_items__isnull=True)
131             .values("order_items__product")
132             .annotate(sold=Sum("order_items__amount"))
133             .order_by()
134         )
135         return {
136             item[0]: item[1]
137             for item in qs.values_list("order_items__product__product__name", "sold")
138         }
139 
140     @property
141     def payment_method_sales(self):
142         qs = (
143             self.orders.values("payment__type")
144             .annotate(sold=Sum("order_items__total"))
145             .order_by()
146         )
147         return {item[0]: item[1] for item in qs.values_list("payment__type", "sold")}
148 
149     @property
150     def user_orders_allowed(self):
151         return self.selforderperiod_set.filter(
152             start__lte=timezone.now(), end__gt=timezone.now()
153         ).exists()
154 
155     @property
156     def user_order_period(self):
157         qs = self.selforderperiod_set.filter(
158             start__lte=timezone.now(), end__gt=timezone.now()
159         )
160         if qs.exists():
161             return qs.first()
162         return None
163 
164     def __str__(self):
165         if self.title and self.title != "":
166             return f"Shift {self.pk} - {self.title}"
167         return f"Shift {self.pk}"
168 
169 
170 class SelfOrderPeriod(models.Model):
171     class Meta:
172         verbose_name = _("self-order period")
173         verbose_name_plural = _("self-order periods")
174         ordering = ["start"]
175 
176     shift = models.ForeignKey(Shift, blank=False, null=False, on_delete=models.CASCADE)
177     start = models.DateTimeField(
178         verbose_name=_("start"),
179         blank=False,
180         null=False,
181     )
182     end = models.DateTimeField(
183         verbose_name=_("end"),
184         blank=False,
185         null=False,
186         help_text=_(
187             "After this moment, users cannot place orders themselves anymore in this shift."
188         ),
189     )
190 
191     def __str__(self):
192         return f"Self-order period for shift {self.shift.pk}"
193
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/website/sales/models/shift.py b/website/sales/models/shift.py
--- a/website/sales/models/shift.py
+++ b/website/sales/models/shift.py
@@ -66,7 +66,7 @@
         super().clean()
         errors = {}
 
-        if self.orders.filter(created_at__lt=self.start):
+        if self.pk is not None and self.orders.filter(created_at__lt=self.start):
             errors.update(
                 {
                     "start": _(

{"golden_diff": "diff --git a/website/sales/models/shift.py b/website/sales/models/shift.py\n--- a/website/sales/models/shift.py\n+++ b/website/sales/models/shift.py\n@@ -66,7 +66,7 @@\n         super().clean()\n         errors = {}\n \n-        if self.orders.filter(created_at__lt=self.start):\n+        if self.pk is not None and self.orders.filter(created_at__lt=self.start):\n             errors.update(\n                 {\n                     \"start\": _(\n", "issue": "Cannot create new shifts: ValueError: 'Shift' instance needs to have a primary key value before this relationship can be used.\nSentry Issue: [CONCREXIT-KK](https://sentry.io/organizations/thalia/issues/3788518453/?referrer=github_integration)\n\n```\nValueError: 'Shift' instance needs to have a primary key value before this relationship can be used.\n(14 additional frame(s) were not displayed)\n...\n  File \"django/forms/models.py\", line 492, in _post_clean\n    self.instance.full_clean(exclude=exclude, validate_unique=False)\n  File \"django/db/models/base.py\", line 1452, in full_clean\n    self.clean()\n  File \"sales/models/shift.py\", line 69, in clean\n    if self.orders.filter(created_at__lt=self.start):\n  File \"django/db/models/manager.py\", line 85, in manager_method\n    return getattr(self.get_queryset(), name)(*args, **kwargs)\n  File \"django/db/models/fields/related_descriptors.py\", line 687, in get_queryset\n    raise ValueError(\n```\n", "before_files": [{"content": "from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.db.models import Count, Q, Sum\nfrom django.db.models.expressions import Value\nfrom django.db.models.functions import Coalesce\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\n\nfrom queryable_properties.managers import QueryablePropertiesManager\nfrom queryable_properties.properties import AggregateProperty, RangeCheckProperty\n\nfrom activemembers.models import MemberGroup\nfrom payments.models import PaymentAmountField\nfrom sales.models.product import ProductList\n\n\nclass Shift(models.Model):\n    class Meta:\n        permissions = [\n            (\"override_manager\", _(\"Can access all shifts as manager\")),\n        ]\n\n    objects = QueryablePropertiesManager()\n\n    start = models.DateTimeField(\n        verbose_name=_(\"start\"),\n        blank=False,\n        null=False,\n    )\n    end = models.DateTimeField(\n        verbose_name=_(\"end\"),\n        blank=False,\n        null=False,\n        help_text=_(\n            \"The end time is only indicative and does not prevent orders being created after the shift has ended. This only happens after locking the shift.\"\n        ),\n    )\n\n    title = models.CharField(\n        verbose_name=_(\"title\"), blank=True, null=True, max_length=100\n    )\n\n    product_list = models.ForeignKey(\n        ProductList,\n        verbose_name=_(\"product list\"),\n        blank=False,\n        null=False,\n        on_delete=models.PROTECT,\n    )\n\n    managers = models.ManyToManyField(\n        MemberGroup, verbose_name=_(\"managers\"), related_name=\"manager_shifts\"\n    )\n\n    locked = models.BooleanField(\n        verbose_name=_(\"locked\"),\n        blank=False,\n        null=False,\n        default=False,\n        help_text=_(\n            \"Prevent orders being changed or created for this shift. This will also clean up all unpaid orders in this shift.\"\n        ),\n    )\n\n    def clean(self):\n        super().clean()\n        errors = {}\n\n        if self.orders.filter(created_at__lt=self.start):\n            errors.update(\n                {\n                    \"start\": _(\n                        \"There are already orders created in this shift before this start time.\"\n                    )\n                }\n            )\n\n        if self.end and self.start and self.end <= self.start:\n            errors.update({\"end\": _(\"End cannot be before start.\")})\n\n        if errors:\n            raise ValidationError(errors)\n\n    def save(\n        self, force_insert=False, force_update=False, using=None, update_fields=None\n    ):\n        if self.locked:\n            self.orders.filter(\n                (Q(payment__isnull=True) & Q(total_amount__gt=0))\n                | Q(order_items__isnull=True)\n            ).delete()\n\n        return super().save(force_insert, force_update, using, update_fields)\n\n    active = RangeCheckProperty(\"start\", \"end\", timezone.now)\n\n    total_revenue = AggregateProperty(\n        Sum(\n            Coalesce(\"orders___total_amount\", Value(0.00)),\n            output_field=PaymentAmountField(allow_zero=True),\n        )\n    )\n\n    total_revenue_paid = AggregateProperty(\n        Sum(\n            Coalesce(\"orders__payment__amount\", Value(0.00)),\n            output_field=PaymentAmountField(allow_zero=True),\n        )\n    )\n\n    num_orders = AggregateProperty(\n        Count(\n            \"orders\",\n        )\n    )\n\n    num_orders_paid = AggregateProperty(\n        Count(\n            \"orders\",\n            filter=Q(orders___is_free=True)\n            | Q(\n                orders__payment__isnull=False,  # or the order is free\n            ),\n        )\n    )\n\n    @property\n    def product_sales(self):\n        qs = (\n            self.orders.exclude(order_items__isnull=True)\n            .values(\"order_items__product\")\n            .annotate(sold=Sum(\"order_items__amount\"))\n            .order_by()\n        )\n        return {\n            item[0]: item[1]\n            for item in qs.values_list(\"order_items__product__product__name\", \"sold\")\n        }\n\n    @property\n    def payment_method_sales(self):\n        qs = (\n            self.orders.values(\"payment__type\")\n            .annotate(sold=Sum(\"order_items__total\"))\n            .order_by()\n        )\n        return {item[0]: item[1] for item in qs.values_list(\"payment__type\", \"sold\")}\n\n    @property\n    def user_orders_allowed(self):\n        return self.selforderperiod_set.filter(\n            start__lte=timezone.now(), end__gt=timezone.now()\n        ).exists()\n\n    @property\n    def user_order_period(self):\n        qs = self.selforderperiod_set.filter(\n            start__lte=timezone.now(), end__gt=timezone.now()\n        )\n        if qs.exists():\n            return qs.first()\n        return None\n\n    def __str__(self):\n        if self.title and self.title != \"\":\n            return f\"Shift {self.pk} - {self.title}\"\n        return f\"Shift {self.pk}\"\n\n\nclass SelfOrderPeriod(models.Model):\n    class Meta:\n        verbose_name = _(\"self-order period\")\n        verbose_name_plural = _(\"self-order periods\")\n        ordering = [\"start\"]\n\n    shift = models.ForeignKey(Shift, blank=False, null=False, on_delete=models.CASCADE)\n    start = models.DateTimeField(\n        verbose_name=_(\"start\"),\n        blank=False,\n        null=False,\n    )\n    end = models.DateTimeField(\n        verbose_name=_(\"end\"),\n        blank=False,\n        null=False,\n        help_text=_(\n            \"After this moment, users cannot place orders themselves anymore in this shift.\"\n        ),\n    )\n\n    def __str__(self):\n        return f\"Self-order period for shift {self.shift.pk}\"\n", "path": "website/sales/models/shift.py"}], "after_files": [{"content": "from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.db.models import Count, Q, Sum\nfrom django.db.models.expressions import Value\nfrom django.db.models.functions import Coalesce\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\n\nfrom queryable_properties.managers import QueryablePropertiesManager\nfrom queryable_properties.properties import AggregateProperty, RangeCheckProperty\n\nfrom activemembers.models import MemberGroup\nfrom payments.models import PaymentAmountField\nfrom sales.models.product import ProductList\n\n\nclass Shift(models.Model):\n    class Meta:\n        permissions = [\n            (\"override_manager\", _(\"Can access all shifts as manager\")),\n        ]\n\n    objects = QueryablePropertiesManager()\n\n    start = models.DateTimeField(\n        verbose_name=_(\"start\"),\n        blank=False,\n        null=False,\n    )\n    end = models.DateTimeField(\n        verbose_name=_(\"end\"),\n        blank=False,\n        null=False,\n        help_text=_(\n            \"The end time is only indicative and does not prevent orders being created after the shift has ended. This only happens after locking the shift.\"\n        ),\n    )\n\n    title = models.CharField(\n        verbose_name=_(\"title\"), blank=True, null=True, max_length=100\n    )\n\n    product_list = models.ForeignKey(\n        ProductList,\n        verbose_name=_(\"product list\"),\n        blank=False,\n        null=False,\n        on_delete=models.PROTECT,\n    )\n\n    managers = models.ManyToManyField(\n        MemberGroup, verbose_name=_(\"managers\"), related_name=\"manager_shifts\"\n    )\n\n    locked = models.BooleanField(\n        verbose_name=_(\"locked\"),\n        blank=False,\n        null=False,\n        default=False,\n        help_text=_(\n            \"Prevent orders being changed or created for this shift. This will also clean up all unpaid orders in this shift.\"\n        ),\n    )\n\n    def clean(self):\n        super().clean()\n        errors = {}\n\n        if self.pk is not None and self.orders.filter(created_at__lt=self.start):\n            errors.update(\n                {\n                    \"start\": _(\n                        \"There are already orders created in this shift before this start time.\"\n                    )\n                }\n            )\n\n        if self.end and self.start and self.end <= self.start:\n            errors.update({\"end\": _(\"End cannot be before start.\")})\n\n        if errors:\n            raise ValidationError(errors)\n\n    def save(\n        self, force_insert=False, force_update=False, using=None, update_fields=None\n    ):\n        if self.locked:\n            self.orders.filter(\n                (Q(payment__isnull=True) & Q(total_amount__gt=0))\n                | Q(order_items__isnull=True)\n            ).delete()\n\n        return super().save(force_insert, force_update, using, update_fields)\n\n    active = RangeCheckProperty(\"start\", \"end\", timezone.now)\n\n    total_revenue = AggregateProperty(\n        Sum(\n            Coalesce(\"orders___total_amount\", Value(0.00)),\n            output_field=PaymentAmountField(allow_zero=True),\n        )\n    )\n\n    total_revenue_paid = AggregateProperty(\n        Sum(\n            Coalesce(\"orders__payment__amount\", Value(0.00)),\n            output_field=PaymentAmountField(allow_zero=True),\n        )\n    )\n\n    num_orders = AggregateProperty(\n        Count(\n            \"orders\",\n        )\n    )\n\n    num_orders_paid = AggregateProperty(\n        Count(\n            \"orders\",\n            filter=Q(orders___is_free=True)\n            | Q(\n                orders__payment__isnull=False,  # or the order is free\n            ),\n        )\n    )\n\n    @property\n    def product_sales(self):\n        qs = (\n            self.orders.exclude(order_items__isnull=True)\n            .values(\"order_items__product\")\n            .annotate(sold=Sum(\"order_items__amount\"))\n            .order_by()\n        )\n        return {\n            item[0]: item[1]\n            for item in qs.values_list(\"order_items__product__product__name\", \"sold\")\n        }\n\n    @property\n    def payment_method_sales(self):\n        qs = (\n            self.orders.values(\"payment__type\")\n            .annotate(sold=Sum(\"order_items__total\"))\n            .order_by()\n        )\n        return {item[0]: item[1] for item in qs.values_list(\"payment__type\", \"sold\")}\n\n    @property\n    def user_orders_allowed(self):\n        return self.selforderperiod_set.filter(\n            start__lte=timezone.now(), end__gt=timezone.now()\n        ).exists()\n\n    @property\n    def user_order_period(self):\n        qs = self.selforderperiod_set.filter(\n            start__lte=timezone.now(), end__gt=timezone.now()\n        )\n        if qs.exists():\n            return qs.first()\n        return None\n\n    def __str__(self):\n        if self.title and self.title != \"\":\n            return f\"Shift {self.pk} - {self.title}\"\n        return f\"Shift {self.pk}\"\n\n\nclass SelfOrderPeriod(models.Model):\n    class Meta:\n        verbose_name = _(\"self-order period\")\n        verbose_name_plural = _(\"self-order periods\")\n        ordering = [\"start\"]\n\n    shift = models.ForeignKey(Shift, blank=False, null=False, on_delete=models.CASCADE)\n    start = models.DateTimeField(\n        verbose_name=_(\"start\"),\n        blank=False,\n        null=False,\n    )\n    end = models.DateTimeField(\n        verbose_name=_(\"end\"),\n        blank=False,\n        null=False,\n        help_text=_(\n            \"After this moment, users cannot place orders themselves anymore in this shift.\"\n        ),\n    )\n\n    def __str__(self):\n        return f\"Self-order period for shift {self.shift.pk}\"\n", "path": "website/sales/models/shift.py"}]}