我有一个Trip
该模型可以让多个参与者和一个所有者订阅一次给定的旅行。参与者是在网站上注册的用户,但我也希望能够将“离线”用户添加到旅行中,即在网站上没有帐户的用户,以便我可以跟踪所有即将到来的用户。
所有者和参与者链接到 Userena 用户个人资料(附带问题:可能直接链接到User
会更好?但是我怎样才能让 full_name 在内联管理中看到选择呢?)
class Trip(models.Model):
name = models.CharField('trip name', max_length=200)
type = models.ForeignKey(Category, related_name='categories')
.
.
.
slug = models.SlugField('trip slug', max_length=100)
owner = models.ForeignKey(UserProfile, related_name='owner')
participants = models.ManyToManyField(UserProfile, blank=True, null=True, related_name='participants')
is_public = models.BooleanField("is visible?",db_index=True)
class ParticipationInline(admin.TabularInline):
model = Trip.participants.through
extra = 3
class TripAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name in ('desc',):
return db_field.formfield(widget=TinyMCE(
attrs={'cols': 100, 'rows': 20},
mce_attrs={'external_link_list_url': reverse('tinymce.views.flatpages_link_list')},
))
return super(TripAdmin, self).formfield_for_dbfield(db_field, **kwargs)
inlines = [
ParticipationInline,
]
exclude = ('participants',)
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'type', 'date', 'dest','owner', 'is_public')
list_filter = ['date', 'type']
search_fields = ['name', 'dest', 'desc']
date_hierarchy = 'date'
class Media:
js = ('js/tiny_mce/tiny_mce.js',
'js/tiny_mce/textareas.js',)
admin.site.register(Trip, TripAdmin)
所以当我添加一个Trip
通过管理界面,我想首先从现有注册用户中选择一个参与者,如果我在那里找不到他们,我希望能够内联添加一个新的“离线”参与者。实现这一目标的最佳方法是什么?
- 有两个配置文件继承自我的
UserProfile
?
- 有一个单独的离线用户模型和两个ManyToMany关系
Trip
?
- 还有更好的办法吗?
Edit在赫德发表评论后。
我创建OfflineUser
正如 GenericRelation 对我的建议Trip
:
class OfflineUser(models.Model):
first_name = models.CharField(_('first'), max_length=30)
last_name = models.CharField(_('last'), max_length=30)
...
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey("content_type", "object_id")
class Trip(models.Model):
...
owner = models.ForeignKey(UserProfile, related_name='owner')
participants = models.ManyToManyField(UserProfile, blank=True, null=True, related_name='participants')
offline_users = generic.GenericRelation(OfflineUser)
添加后OfflineUserInline
我可以将注册用户和离线用户添加到我的Trip
!
然后我可以列出Trip
两种类型的参与者都是这样的:
{% if request.user.is_staff %}
<ul>
{% for participants in object.participants.all %}
<li> {{ participants.full_name }}
</li>
{% empty %}
No registered users!
{% endfor %}
{% for participants in object.offline_users.all %}
<li> {{ participants.full_name }}
</li>
{% empty %}
No offline users!
{% endfor %}
</ul>
{% endif %}
所以它在某种程度上有效,现在我有一种奇怪的感觉,我没有完全理解赫德的回答......
每次我想对参与者做一些事情(计数、列出他们等)时,我都需要做两次?