Aamu
Aamu

Reputation: 3601

django - auto populating the fields in the models

Please have a look at my models.py.

models.py:

class Thread(models.Model):
    pass

class ThreadParticipant(models.Model):
    thread = models.ForeignKey(Thread)
    user = models.ForeignKey(User)

class Message(models.Model):
    thread = models.ForeignKey(Thread)
    sent_date = models.DateTimeField(default=datetime.now)
    body = models.TextField()
    user = models.ForeignKey(User)

class MessageReadState(models.Model):
    message = models.ForeignKey(Message)
    user = models.ForeignKey(User)
    read_date = models.DateTimeField()

I am having two problems when I try to create a new message:

  1. How do I auto populate the Thread with its primary key whenever I create a new message, without manually creating a new thread?
  2. How to create a new user if the user is not in the the ThreadParticipant, or else don't create a new user?

I think I can solve this all in the views.py, but I think it will be better to solve this in the models.py. Please help me solve the problem. I would be very grateful. Thank you.

Edit:

Suppose, I need to create a new message. The steps will be:

  1. I will have to create a new Thread first.
  2. And similarly, I will have to create a new ThreadParticpant for that Thread (pk).
  3. I will have to get that user who sent the message to create a new user (participant) for that ThreadParticipant.

So my problem is, when I try to create a new message, I don't want to go and create a new thread first or create a new set of ThreadParticipants. I just want it to be on the background, so that all I have to do is create a message and send it to the user. Hence, my questions are:

  1. How do I create a new Thread in the background automatically and use its pk for the ThreadParticipant?
  2. So, if the ThreadParticipant has its new Thread to relate, how do I get the user who sent the message and create a new user for that set of thread participants?

Can it be done by overriding the save method or class method?

Upvotes: 0

Views: 121

Answers (1)

Arpit
Arpit

Reputation: 953

For your 1st question, I believe you should use F function of django-dynamic-fixture.
And for 2nd question, use this User.objects.get_or_create(conditions)

Upvotes: 1

Related Questions