1

I have models

class Event(models.Model): some_field = models.CharField() class Ticket(models.Model): event = models.ForeignKey(Event) 

How i can set model ticket field event, event with some_field field? Example:

Ticket.objects.create(event__some_field = 'value') 

how can you achieve this?

ps. i can't use ticket.event_id = event_id and ticket.event = event in my situation (i don't want to request to database)

5
  • 2
    But at this point your ticket has not been linked to an event object in the first place, you will first need to assign one, for example with ticket.event = myevent. Commented May 1, 2019 at 9:35
  • Yes, I know, but let's say that I already have an event created, and I do not want to make a request for get event Commented May 1, 2019 at 9:39
  • 1
    Do you know the event_id of the event? If so you could set ticket.event_id=event_id(this will not make a "request" to the database). Commented May 1, 2019 at 10:07
  • ticket.event_id=event_id(this will not make a "request" to the database) - really? :( Commented May 1, 2019 at 10:12
  • Yes, it will not make a request. Commented May 1, 2019 at 11:16

1 Answer 1

2

You have to create and save the Event instance separate from creating the Ticket.

event = Event(some_field='value') event.save() ticket = Ticket() ticket.event = event ticket.save() 

And if you wanted to update an already existing event related to a ticket:

ticket.event.some_field = "new value" ticket.event.save() # no need to save ticket here, because nothing has changed in the relationship between ticket and event 
Sign up to request clarification or add additional context in comments.

7 Comments

i have been events when i create a ticket, just i don't want to make a request to database
Do you mean you already have the event instance? Or that you don't have it and you want to create a ticket for an event you don't hold in memory, but without hitting the DB?
no, i don't have event instance, but i have events in database
i don't want to make request to database for get event next create ticket
okey, i solved my problem, I am all like that need make request to database for get event before create ticket
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.