1 | | When a Model with a GenericForeignKey field is assigned, the model's id is overwritten with the GenericForeignKey's id on assignment. |
2 | | |
3 | | I am using a mySQL database (Ver 14.14 Distrib 5.6.28), Python3(3.7.2), and django(2.1.7) |
4 | | |
5 | | Models: |
6 | | {{{ |
7 | | class Incident(models.Model): |
8 | | start_timestamp = models.DateTimeField(auto_now=True) |
9 | | class Meta: |
10 | | abstract = True |
11 | | |
12 | | class DailyLog(Incident): |
13 | | date = models.DateField(auto_now=True) |
14 | | entries = GenericRelation(DailyLogHistory, object_id_field='id', content_type_field='incident_type') |
15 | | |
16 | | class Data(models.Model): |
17 | | creator = models.CharField(max_length=255) |
18 | | creator_details = models.TextField(blank=True, null=True, default=None) |
19 | | timestamp = models.DateTimeField(auto_now=True) |
20 | | incident_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, primary_key=False, unique=False, blank=True, null=True) |
21 | | incident_object = GenericForeignKey('incident_type', 'id') |
22 | | class Meta: |
23 | | abstract = True |
24 | | |
25 | | class DailyLogHistory(Data): |
26 | | selections = CSVField(blank=True, null=True, default=None) |
27 | | |
28 | | }}} |
29 | | |
30 | | code that produces the bug: |
31 | | |
32 | | {{{ |
33 | | incident = DailyLog.objects.get(id=1) |
34 | | |
35 | | x = DailyLogHistory( |
36 | | selections=['123456'], |
37 | | creator='sam', |
38 | | ) |
39 | | x.save() |
40 | | |
41 | | print(x) # Shows the correct auto-incremented id != 1 |
42 | | x.incident_object = incident |
43 | | print(x) # Shows that id == 1 |
44 | | |
45 | | }}} |
| 1 | Not a bug. Stupid error on my part. The GenericForeignKey id is the same as that specified in the model. |