开发者

Django ModelField for an object that is the target of ForgeinKeys on other objects

开发者 https://www.devze.com 2023-03-11 01:21 出处:网络
I have some Django objects like this: class Award(Model): name = CharField(...) date = DateTimeField(...)

I have some Django objects like this:

class Award(Model):
  name = CharField(...)
  date = DateTimeField(...)


class Book(Model):
  name = CharField(...)
  award = ForgeinKey(Award, blank=True)

(i.e. each Book may or may not have one award)

I want to make a form for adding/editing Awards. Assume lots of Books have already been created. Initially I created a ModelForm like this:

class AwardForm(ModelForm):
    class Meta:
      model = Award

which created a correct form with all the data, however there was no way to add books to the award (or mark this award as applicable to the books that were selected).

I was going to manually add a ModelMultipleChoiceField to the AwardForm (with a queryset for the Books), then add logic to is_valid that would check the Books that were selected, and add something to save to go through the selected Books and set the forgein key on that object to this object.

However, Is there a good 'django' way to do this automatically? i.e. just add a certain field to the Form which will do that all itself? If I were to change the Book.award to be a Award.books manytomany key it would probably do all this automatically, but I like the internal logic of having th开发者_开发百科at as a forgeinkey on the Book.


I was just going to suggest using Inline's but upon re-reading your question the hard part is selecting objects that already exist and linking them to the Award that you are editing.

The way that you have suggested is the first way that I would do it, and the only other way I can think of would involve hacking away at some of the methods on your AwardAdmin to add in the functionality that you desire.

Using the ModelMultipleChoiceField though seems like quite a clean way of doing it to be honest, especially since you shouldn't really need much/any editing of the save method as the field should handle that itself?

0

精彩评论

暂无评论...
验证码 换一张
取 消