M
M
matveyvarg2016-05-04 21:00:24
Django
matveyvarg, 2016-05-04 21:00:24

How to automatically fill an empty model field with a link?

There is this model:

class Vote(models.Model):


  record = models.OneToOneField(Record)

  voted_by = models.ForeignKey(UserProfile)

How to automatically populate the record field? It is necessary that the record field be filled in automatically by already created objects of the Record class.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Sergeev, 2016-05-04
@SergeevAI

default=1
Or write a signal

B
baterson, 2016-05-06
@baterson

If you need to add a connection when creating a model Vote, then you can overload the methodsave()

class Vote(models.Model):
    
    def save(self, *args, **kwargs):
        #Проверяем, что объекта еще нет в базе
        if self.pk is None:
            record = Record.objects.create(#заполняете нужные поля)
            self.record = record
        super(Vote, self).save(*args, **kwargs)

It is not entirely clear from the question what exactly is needed, if you need an already created object Record, you can simply take it from the database, and not create a new one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question