views:

214

answers:

2

I have this Model:

class Occurrence(models.Model):
    id = models.AutoField(primary_key=True, null=True)
    reference = models.IntegerField(null=True, editable=False)

    def save(self):
         self.reference = self.id
         super(Occurrence, self).save()

I want for the reference field to be hidden and at the same time have the same value as id. This code works if the editable=True but if i want to hide it it doesnt change the value of reference.

how can i fix that?

+1  A: 

Why not just use the id then? And you can expose it under the name 'reference' by making it a property, but it won't show up in any ModelForms, inlcuding the admin:

@property
def reference(self):
  try:
    return self.id
  except AttributeError: #in case the object is not yet saved
    return None
stevejalim
A: 

Hi, there are a couple of things I'd like to comment about your code. First of all in save it should say reference and not collection, and the super should be idented inside save. You where forgetting to pass the arguments in super too. It should look like this:

class Occurrence(models.Model):
    id = models.AutoField(primary_key=True, null=True)
    reference = models.IntegerField(null=True, editable=False)

    def save(self):
        self.reference = self.id    
        super(Occurrence, self).save(*args, **kwargs)

This will work always despite the editable value. Editable is there just for the admin. By the way, I assume you are talking about hiding reference in the admin. As the id never changes once it's saved you can use it's value instead of the reference one.

Hope this helps.

rasca